如何使用 JQuery 循环访问单独 HTML 文件的元素?
到目前为止我有这个:
var x = $('<div>').load('<separate html file> #<id>');
console.log(x[0]);
现在我想循环遍历变量 x
中的元素。最好使用JQuery each loop
.
x
保存 <separate html file>
中的元素列表每个都有 <id>
指定。
console.log(x[0])
的输出看起来像这样(其中 <id>
是上面指定的 id:
<div>
<div id=<id> >Stuff</div>
<div id=<id> >Stuff</div>
<div id=<id> >Stuff</div>
</div>
最佳答案
您需要等到 load
操作已完成,您可以通过设置成功回调函数来完成此操作。
接下来,您需要有一些东西可以循环。我假设您的结果更多是 HTML,因此我们可以循环遍历 children容器的。
最后,您可以执行each
循环:
// Perform the load operation (hard-coded response here) and supply a success callback:
var x = $( "#result" ).load(
"<div><div id=1 >Stuff</div><div id=2>Stuff</div><div id=3>Stuff</div><div>", function() {
// Find the first div element within the container and loop through its children
$("#result").find("div").children().each(function(){
// Access the element and do whatever you need to:
console.log(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
<div>
<div id=1 >Stuff</div>
<div id=2>Stuff</div>
<div id=3>Stuff</div>
</div>
</div>
关于javascript - 使用 JQuery 循环遍历单独 HTML 文件的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42032815/