gpt4 book ai didi

javascript - jquery 找不到每个 ID 的 div 元素

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:50 24 4
gpt4 key购买 nike

好吧,我算不上 js 新手,但这实在是太奇怪了。

我这里有一个 wordpress,想添加一个评论框,如果框可见,当用户向下滚动到那个框时,它应该按 ajax 加载评论,这样我可以节省性能并且不需要加载评论每次有人请求页面时。

为此,我将以下代码片段添加到我的 wp single.php 帖子模板中:

            <?php /** Begin Post Content **/ ?>     

<?php the_content(); ?>

<?php wp_link_pages('before=<div class="pagination">'._r('Pages:').'&after=</div><br />'); ?>

<div id="vbcomments_box" style="display:visible">asd</div>

<?php print vb_comments_ajax($post); ?>

<?php /** Begin Tags **/ ?>

第 4 和第 5 行来 self ,它引入了一个带有 id 和随机内容的 div#vbcomments_box。

之后,我调用一个函数将 javascript 代码注入(inject)到页面中(我知道这可能更漂亮,但出于开发目的,这将暂时保留。):

<script>

(function(){window.setInterval(function() {
console.log('the element is: ', $('#vbcomments_box'));
if($('#vbcomments_box').is(':visible')){
vbc_is_visible();
}
}, 1000);

// Function / event that will be started and stopped
function vbc_is_visible() {
alert('HALLO');
$("#vbcomments_box").html("LOADING...");
}

console.log("Inside script");})();

</script>

这只是设置了一个计时器来测试选择器 $('#vbcomments_box').is(':visible')

实际情况是,$('#vbcomments_box') 始终为空。我测试了一切。我将 vbcomments_box 更改为一个类,我在 # 之前添加了 div,我尝试根据 document.getElementById 查找它(幸运的是找到了它,但我无法用它做任何事情)

那么为什么 jquery 找不到这个简单的 div 元素,我 10000% 确定它存在于源代码中,并且在将 div 放入源代码后调用 js 东西?

我做错了什么?

控制台说:

the element is:  null (index):611
Uncaught TypeError: Cannot call method 'is' of null

最佳答案

试试这个:

<?php the_content(); ?>

<?php wp_link_pages('before=<div class="pagination">'._r('Pages:').'&after=</div><br />'); ?>

<div id="vbcomments_box" style="display:visible;">asd</div>

<?php print vb_comments_ajax($post); ?>

<?php /** Begin Tags **/ ?>

……

<script>

(function(){window.setInterval(function() {
console.log('the element is: ', jQuery('#vbcomments_box'));
if(jQuery('#vbcomments_box').is(':visible')){
vbc_is_visible();
}
}, 1000);

// Function / event that will be started and stopped
function vbc_is_visible() {
alert('HALLO');
jQuery("#vbcomments_box").html("LOADING...");
}

console.log("Inside script");})();

</script>

关于javascript - jquery 找不到每个 ID 的 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515252/

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