使用Ajax/jQuery解析HTML字符串

5 html ajax jquery

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

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

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

moo.html包含

<div id='test'>zebra</div>
<div id='foo'>bar</div>
Run Code Online (Sandbox Code Playgroud)

我怎么能得到斑马和酒吧?

Roa*_*rth 14

我认为换行moo.html可能会让你沮丧.

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

你需要的是只获取div你的html中的s:

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