javascript - 使用 JQuery 循环遍历单独 HTML 文件的元素

标签 javascript jquery html

如何使用 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/

相关文章:

javascript - 将事件传递给 jQuery 插件

javascript - 使用 javascript 根据一个公共(public)属性对多个数组进行分组

javascript - plotly - 响应宽度,固定高度

javascript - 从 .js 库调用网页中的 Javascript 函数

jquery - jquery中动态删除文本框

html - 通过根据 html 标签调整单元格大小,使用 UITextView 在 UITableViewCell 中显示 html [不是 UILabel!]

javascript - Jasny Bootstrap offcanvas 菜单 - ajax 'close' 导致关闭问题

javascript - 在 jQuery 中追加字符串变量

javascript - 一个链接中的 jQuery 定位错误

javascript - Jquery 从另一个页面添加 HTML