【问题标题】:javascript doesn't keep new tag content oustide a function?javascript不会将新标签内容保留在函数之外?
【发布时间】:2016-03-10 12:11:39
【问题描述】:

我有一个问题,我可能知道如何解决它,但我不知道它为什么存在。 在 html 代码中我有一个空标签 ul

     .....
     <ul></ul>
      ....

然后在javascript中我有一个向这个标签添加内容的函数:

$(document).ready(function(){
......
function test(){
    $("ul").html("<li>blablabla</li>...");
    alert( $("ul").html());  //alert 1 work like a charm it show the exact content
}
 test();
 alert( $("ul").html()); //alert 2 show that ul is empty :(
 .....
 }

现在我想通过使用函数来组织我的代码,但这个问题迫使我留在同一个函数中。等待您的帮助。谢谢

【问题讨论】:

  • 我认为这不是您的完整代码。
  • 代码显示两个警报jsfiddle demo中的html。所以肯定有其他事情你没有显示
  • 有什么问题?行为对我来说很好。
  • 其实代码比较复杂,比较长,不过我会尽量发布一个简单的

标签: javascript jquery html function tags


【解决方案1】:

谢谢大家,我终于找到了问题所在,这是我的问题的更新:

我有一个问题,我可能知道如何解决它,但我不知道为什么 甚至存在。在 html 代码中我有一个空标签 ul

     .....
     <ul></ul>
      ....

然后在javascript中我有一个向这个标签添加内容的函数:

  $(document).ready(function(){
      ......
      test();
      alert( $("ul").html()); //alert 2 show that ul is empty :(
      .....
     }

 function test(selected){
     $.post("http://localhost/htmlTraining/php/liste.php",{classe: selected},function(data){ 
         $("ul").html('<img id="next" src="images/next.ico"/><img id="prev" src="images/prev.ico"/>'+data);
           alert( $("ul").html());  //alert 1 work like a charm it show the exact content
       });
}

现在我想通过使用函数来组织我的代码,但是这个 问题迫使我留在同一个函数中。等待你 帮助。谢谢

在此代码中,alert 2 不起作用,因为它在函数 test 完成执行之前运行。而此时tag ul 仍然是空的。我通过使用function setinterval()alert2 发现了这个问题,一段时间后alert2 工作正常。

我学到的是:

function1();
function2();

如果您想在 function2 中使用来自 function1 的数据,请确保它们已准备好。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多