jquery .load() page then parse html

∥☆過路亽.° 提交于 2019-12-18 12:17:14

问题


I have used the line below in my app. But now I need to parse the html loaded before I show it. Whats the best way to get certain html elements.

$("#div").load("page.html");

Thanks

UPDATED

Now I am using this but having trouble geting the title attribute of a div with the id "div".

function get_title()
{
    $.get("test.html", function(data) {
        var data = $(data);
        var title = $("#div", data).attr("title");

        alert(title);
    });
}

The html in the var data looks like this.

<div id="div" title="title example">
<p>
    Content
</p>
<p>
    Content
</p>
</div>

Thanks again


回答1:


You can use the semi-equivalent expanded version of $.get(), like this:

$.get("page.html", function(data) {
  var data = $(data);
  //do something
  $("#div").html(data);
});

Note that calling .html(data) in this case is just a shortcut for .empty().append(data).


Or, if post-processing is an option, just use the .load() callback, like this:

$("#div").load("page.html", function() {
  $(this).find(".class").remove(); //just an example
});



回答2:


Instead of calling .load(), you should call $.get to perform an AJAX request and manually process the response.




回答3:


jQuery.ajax({
    url:'your_url',
    type:'get',
    dataType:'html',
    success:function(data)
   { 
       var _html= jQuery(data);
       //do some thing with html eg: _html.find('div').addClass('red')
       jQuery('#target').html(_html);
   }
});


来源:https://stackoverflow.com/questions/3856590/jquery-load-page-then-parse-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!