jquery:标签和文字分开

jquery: separate tag and text

我有:

// $(this): <span class="class1"><span class="class2"></span> Some text</span>
$(this).children().each(function () {
    console.log(this);
});

从控制台我只得到了 class2 的跨度,我怎样才能得到文本?类似于:

['<span class="class2"></span>', 'Some text']

注意 .contents().children() 之间的区别。你需要前者

虽然 .children() return 所有可用元素,.contents 也 return 文本和评论

$(this).children() 只会 return 个作为元素的子节点。

您需要使用 $(this).contents() 来获取所有节点,包括文本节点。 :)

然后您可以过滤这些节点以仅获取元素和文本(参见 node types):

$(this).contents().filter(function() {
  return (this.nodeType === 1) || (this.nodeType === 3);
})

你可以得到这样的输出

jQuery(".class1").contents()