使用 Ajax/jQuery 解析 HTML 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1529464/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:38:54  来源:igfitidea点击:

Parsing HTML String with Ajax/jQuery

jqueryhtmlajax

提问by Roatin Marth

I asked at Parsing HTML String with jQueryhow 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.

我在Parsing HTML String with jQuery问我如何在 html 字符串上使用 jQuery。这一切都有效,但是当我将它应用于 ajax 时 - 它不起作用。这是代码。

<script>
  var url = 'moo.html';

  $.ajax({
    url: url,
    success: function ( code )
    {
      html = $(code);
      html.each(function() {
        alert( $(this).html() );
      });
    }
  });
</script>

moo.html contains

moo.html 包含

<div id='test'>zebra</div>
<div id='foo'>bar</div>

How can I get zebra and bar?

我怎样才能得到斑马和酒吧?

回答by Roatin Marth

I think newlines in moo.htmlmay be tripping you up.

我认为换行符moo.html可能会让你绊倒。

Any newlines in your html will end up being parsed by jQuery and kept as text node elements "\n". As a result $(code).eachwill 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).

html 中的任何换行符最终都会被 jQuery 解析并保留为文本节点元素"\n"。因此,$(code).each当这些节点中的第一个被命中并调用.html()它时将停止迭代(html()不对非 Element 节点类型进行操作)。

What you need is to grab only the divs in your html:

您需要的是仅获取divhtml 中的s:

var divs = $(code).filter(function(){ return $(this).is('div') });
divs.each(function() {
    alert( $(this).html() )
})

回答by Shrikant Sharat

try $('div', code).each instead.. like so...

试试 $('div', code).each 代替......像这样......

$('div', code).each( function () {
  alert($(this).text());
});

I haven't tested it though...

不过我还没有测试过...

回答by Darko Z

Try:

尝试:

html = $("div", code);
html.each(function() {
    alert($(this).html());
});

The reason you can't do it the way you have it, is because when parsing HTML jQuery wants to have a single root element. If it doesn't then you have to do it the way above. The following HTML/JS would also work:

你不能按照你的方式去做的原因是,在解析 HTML 时,jQuery 想要有一个单一的根元素。如果没有,那么你必须按照上面的方法来做。以下 HTML/JS 也可以使用:

var html = $(code);
html.children().each(....);

<div>
    <div id='test'>zebra</div>
    <div id='foo'>bar</div>
</div>