jquery .load() 页面然后解析 html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3856590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery .load() page then parse html
提问by moo
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.
我在我的应用程序中使用了下面的行。但是现在我需要在显示之前解析加载的 html。获取某些 html 元素的最佳方法是什么。
$("#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".
现在我正在使用它,但无法获取 id 为“div”的 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.
var 数据中的 html 看起来像这样。
<div id="div" title="title example">
<p>
Content
</p>
<p>
Content
</p>
</div>
Thanks again
再次感谢
回答by Nick Craver
You can use the semi-equivalent expanded version of $.get()
, like this:
您可以使用 的半等效扩展版本$.get()
,如下所示:
$.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)
.
请注意,调用.html(data)
在这种情况下,仅仅是一个捷径.empty().append(data)
。
Or, if post-processing is an option, just use the .load()
callback, like this:
或者,如果后处理是一个选项,只需使用.load()
回调,如下所示:
$("#div").load("page.html", function() {
$(this).find(".class").remove(); //just an example
});
回答by SLaks
Instead of calling .load()
, you should call $.get
to perform an AJAX request and manually process the response.
.load()
您应该调用$.get
来执行 AJAX 请求并手动处理响应,而不是调用。
回答by Praveen Prasad
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);
}
});