ajax 加载内容的 jquery 选择器失败
我有一个通过 ajax 加载的对话框。该ajax的paylaod包含html和javascript。
该对话框显示得很好,并且该有效负载中包含的 JS 会执行。
但是,我无法从有效负载中的 JS 选择任何元素(无论是按 id、类还是元素类型)。
假设有效负载有:
<div>
<ul id="testid">
<li>A</li>
<li>B</li>
</ul>
</div>
<script type="text/javascript">
$(document).ready(function() {
console.info('test: ' + $("#testid").length);
});
</script>
这会导致 test: 0 出现在控制台中。
如果我将选择器更改为选择“body”,则会产生非零值。
显然,加载的内容正在显示,并且它包含的 JS 正在执行,我的理解是 .ready() 调用应该允许更新 DOM 时间以包含 html 有效负载。
不幸的是,在这种情况下,我无法直接控制 ajax 加载本身,因为我正在使用一个为我执行对话框功能的框架(zotonic)。
奇怪的是,我拥有的其他 ajax 加载页面具有选择 ajax 加载有效负载中的元素的 JS 正在工作 - 它只是对话框内容(到目前为止)似乎失败了。
我有点不明白为什么会出错。在过去的几天里,我已经完成了尽职调查并搜索了谷歌等,但没有解决方案,所以我想在这里大声寻求帮助。
贾森
I have a dialog that's loaded via ajax. The paylaod of that ajax contains both html and javascript.
The dialog displays just fine and the JS included in that payload executes.
However, I am unable to select any elements (whether its by id, class or element type) from the JS in the payload.
lets say the payload had:
<div>
<ul id="testid">
<li>A</li>
<li>B</li>
</ul>
</div>
<script type="text/javascript">
$(document).ready(function() {
console.info('test: ' + $("#testid").length);
});
</script>
This results in test: 0 appearing in the console.
If I change the selector to select on 'body' then it results in a non-zero value.
Clearly the loaded content is being displayed and the JS it contains IS being executed and my understanding is that the .ready() call should allow the DOM time to be updated to include the html payload.
Unfortunately in this instance I have no direct control over the ajax load itself as I'm using a framework that does the dialog functionality for me (zotonic).
The weird thing is, other ajax loaded pages I have that have JS which selects elements in the ajax loaded payload are working - its just the dialog stuff that (so far) seems to be failing.
I'm at a bit of a loss as to why just this is going wrong. I've done my due diligence and searched google etc for the last couple of days with no solution so thought I'd shout out for help on here.
Jason
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信
ready
仅在页面第一次加载时有效。如果您依赖 AJAX 调用的结果,则需要使用回调,因为该操作是异步的。 zotonic 是否为您提供任何可以使用的挂钩?不然会有点困难。也许您可以在页面加载时像这样轮询 DOM:这将每 750 毫秒查询一次
#testid
页面。如果找到该元素,则间隔将被取消,您应该得到控制台输出。I believe
ready
only works the first time the page loads. If you're depending on the result of an AJAX call, you need to use a callback since the operation is asynchronous. Does zotonic offer you any hooks that you can use? Otherwise it's going to be a little harder. Perhaps you can poll the DOM like this, on page load:This will query they page every 750ms for
#testid
. If it finds the element, the interval is cancelled and you should get a console output.