Parsing HTML String with Ajax/jQuery

后端 未结 3 1429
[愿得一人]
[愿得一人] 2020-12-06 07:49

I asked at 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.

相关标签:
3条回答
  • 2020-12-06 08:18

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

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

    I haven't tested it though...

    0 讨论(0)
  • 2020-12-06 08:33

    I think newlines in moo.html may be tripping you up.

    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).

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

    var divs = $(code).filter(function(){ return $(this).is('div') });
    divs.each(function() {
        alert( $(this).html() )
    })
    
    0 讨论(0)
  • 2020-12-06 08:37

    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:

    var html = $(code);
    html.children().each(....);
    
    <div>
        <div id='test'>zebra</div>
        <div id='foo'>bar</div>
    </div>
    
    0 讨论(0)
提交回复
热议问题