gpt4 book ai didi

javascript - 页面加载后其他元素消失?

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

我想用 Jquery 调用函数 javascript。但页面加载后,所有其他元素都消失了。你可以在这里看到我的代码。我需要你的修复。

<script src='http://code.jquery.com/jquery-1.10.1.min.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$("#recentpost").each(function(){
mytext = "Food";
sticky();
});
});
</script>

<script type="text/javascript">
function sticky(){
document.write("<div class='sample'>"+mytext+"</div>");
}
</script>
<div id="recentpost"></div>

<div>something here disappear after loaded page</div>

感谢您的帮助

最佳答案

这是因为您在页面加载后使用 document.write ,它将新内容写入文档,从而有效地破坏了页面。

您应该使用 DOM 来操作内容,因为所有 HTML 都已写入并解析为对象树。

例如,

function sticky(){
document.getElementById("recentpost").textContent = mytext;
}
<小时/>

此外,您在 ID 上使用 .each() 很奇怪。页面上只能有一个。

所以代替这个:

$("#recentpost").each(function(){
mytext = "Food";
sticky();
});

你会这样做:

$("#recentpost").text("Food");
<小时/>

或者,如果您想使用 sticky() 函数,则应该将值传递给该函数,而不是使用全局变量。

sticky("Food");

function sticky(mytext) {
$("#recentpost").text(mytext);
}

关于javascript - 页面加载后其他元素消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18751371/

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