使用Ajax / jQuery的解析HTML字符串 [英] Parsing HTML String with Ajax/jQuery
问题描述
我问在<一个href="http://stackoverflow.com/questions/1529333/parsing-html-string-with-jquery">http://stackoverflow.com/questions/1529333/parsing-html-string-with-jquery我怎么能在一个HTML字符串使用jQuery。这所有的作品,但是当我将其应用到AJAX - 这是行不通的。这里是code。
I asked at http://stackoverflow.com/questions/1529333/parsing-html-string-with-jquery how I can use jQuery on an html string. That all works, but when I apply it to ajax - it does not work. Here is the code.
<script>
var url = 'moo.html';
$.ajax({
url: url,
success: function ( code )
{
html = $(code);
html.each(function() {
alert( $(this).html() );
});
}
});
</script>
moo.html包含
moo.html contains
<div id='test'>zebra</div>
<div id='foo'>bar</div>
我怎样才能得到斑马吧?
How can I get zebra and bar?
推荐答案
我觉得 moo.html
新行可能会绊倒你。
I think newlines in moo.html
may be tripping you up.
任何换行符在你的HTML最终会被解析的jQuery和保存为文本节点元素\ N
。其结果是 $(code)。每个
将停止迭代时,第一个这些节点被击中,你叫的.html()
就可以了(<$ C C> HTML()不能在非元素节点类型操作$)。
Any newlines in your html will end up being parsed by jQuery and kept as text node elements "\n"
. As a result $(code).each
will stop iterating when the first of these nodes is hit and you call .html()
on it (html()
does not operate on non-Element node types).
您需要的是抓住仅 DIV
在你的HTML:
What you need is to grab only the div
s in your html:
var divs = $(code).filter(function(){ return $(this).is('div') });
divs.each(function() {
alert( $(this).html() )
})
这篇关于使用Ajax / jQuery的解析HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!