javascript - 使用 jquery 抓取 HTML 并操作元素

标签 javascript jquery html ajax

我想从我的第二个站点(子域)获取 html 并使用它来构建此站点的一部分。

HTML 网站:

<head>
<body>

<div id = "items">
  <div id = "#one">
    <ul>
       <li><a href = "#">Click here</a></li>
       <li><img src = "/images.png" /></li>
    </ul>
  </div>

  <div id = "#two">
    <ul>
       <li><a href = "#">Click here</a></li>
       <li><img src = "/images2.png" /></li>
    </ul>
  </div>
 </div>

</body>
</head>

我想做一些事情,比如计算 div 元素的数量、获取列表等。

这是我尝试过的:

$.ajax({ 
 url: '/mysite/items.html', 
success: function(data) { 
  //Need to manipulate here

  var html = $(data);

  var items = $.get(".items", html);
  var numItems = $('.items').length;

  console.log(data); //There is data(Whole HTML is here.)

  console.log(items); //This is undefined??
  console.log(numItems): //This is undefined??

  var raw = html.get(".offers"); //Complains doesnot have a get method??

},
});

最佳答案

从我可以看出你想要什么操作系统

$.ajax({
    url: '/mysite/items.html',
    success: function (data) {
        //Need to manipulate here

        var $html = $(data);

        //use .find() to find elements with class items in data
        var $items = $html.find('.items');
        //use the items object to get the length
        var numItems = $items.length;

        console.log(data);

        console.log($items);
        console.log(numItems):

        //need to use .find() to get the elements matching a selector
        var raw = $htm.find(".offers");

    },
});

关于javascript - 使用 jquery 抓取 HTML 并操作元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21542772/

相关文章:

javascript - 当属性过时时如何处理 semver

Javascript 意外地执行类内的函数

javascript - 将 HTML 添加到 Javascript IF 函数

javascript - 使用点击事件在控制台日志中显示响应

html - 在亚马逊主要网站上搜索一个词(解析)

javascript - 如何无限期地等待,直到页面在 javascript 测试用例中加载

javascript - 遍历另一个 div 中的一类特定 div

javascript - 如何将单个对象的数组合并为一个数组-Js/Jquery

javascript - 运行禁用复选框的 onclick 函数

html - “如何在 <tr> 上添加”mouseover 和 mouseout?