使用 JS/jQuery 动态更新 div 是否依赖于单击同一页面上的元素?



我有一个div,或者更具体地说是一个<p>标签,我想在document.ready上动态更新id="routineInfo",但由于某种原因它似乎不起作用:

$(function() {
$("#routineInfo").html("Routine: Full Body");
});

我开始进行故障排除,我可以通过将 onclick 句柄附加到元素以触发函数来获得所需的效果:

$(".playIt").click(function() {
$("#routineInfo").html("Routine: Full Body");
});

但是,我希望该功能在加载所需页面时发生,因此为了模拟这一点,我将句柄附加到链接到相关页面的元素上,该元素位于不同的页面上:

$(".linkElementOnDifferentPage").click(function() {
$("#routineInfo").html("Routine: Full Body");
});

没用。有人可以向我解释一下吗?

编辑:添加html。

<div class="header">
<div id="info">
<p id="routineInfo"></p>
</div>
</div>

如果您的div(或 p 标签(是动态加载的,则无法保证它在文档就绪函数中可用(主要是在异步渲染视图的情况下(。

$(function() {
setTimeout(function() {
$("#info").append($('<p id="routineInfo"></p>'));
}, 3000);
});
var DivPopulateIntervel = window.setInterval(function() {
if ($("#routineInfo").length > 0) {
$("#routineInfo").html("Routine: Full Body");
window.clearInterval(DivPopulateIntervel);
}
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<div id="info">
</div>
</div>

这里

setTimeout(function() {
$("#info").append($('<p id="routineInfo"></p>'));
}, 3000);

只需在3 秒后将您的#routineInfo添加到文档中即可创建延迟加载或异步效果(仅用于演示目的(。

var DivPopulateIntervel = window.setInterval(function() {
if ($("#routineInfo").length > 0) {
$("#routineInfo").html("Routine: Full Body");
window.clearInterval(DivPopulateIntervel);
}
}, 100);

是每100 毫秒调用一次的setInterval函数,直到呈现所需的div

window.clearInterval(DivPopulateIntervel);

一旦设置了 HTML(或所需的div 可用(,就会删除DivPopulateIntervelIntervel 函数。

最新更新