gpt4 book ai didi

javascript 不会将新标签内容保留在函数之外吗?

转载 作者:行者123 更新时间:2023-11-28 06:16:33 25 4
gpt4 key购买 nike

我有一个问题,我可能知道如何解决它,但我不知道它为什么存在。在 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 :(
.....
}

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

最佳答案

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

I have a problem that I may know how to fix it but I don't know why it even exist. in html code I have an empty tag ul :

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

then in javascript I have a function that add content to this tag:

  $(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
});
}

Now I want to keep my code organised by using funtions but this problem forced me to stay inside the same function. waiting for your help.thanks

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

我学到的是:

function1();
function2();

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

关于javascript 不会将新标签内容保留在函数之外吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35916169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com