jQuery:从 .text() 中排除孩子

新手上路,请多包涵

鉴于此 HTML:

 <a href="#" class="artist">Soulive<span class="create-play">Play</span></a>

我想获取 a 的文本内容(即 this 在我的函数的上下文中), 而不是 span 的文本内容我还剩下:

 Soulive

如果我做:

 $(this).text();

我得到:

 SoulivePlay

如何排除 span 的文本内容?

原文由 daGUY 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 305
2 个回答

一个微插件:

 $.fn.ignore = function(sel) {
  return this.clone().find(sel || ">*").remove().end();
};

…有这个 HTML:

 <div id="test"><b>Hello</b><span> World</span>!!!</div>

将导致:

 var text = $('#test').ignore("span").text(); // "Hello!!!"
var html = $('#test').ignore("span").html(); // "<b>Hello</b>!!!"


如果你想让它更快,你只需要排除直接的孩子……使用 .children( 而不是 .find(

原文由 Roko C. Buljan 发布,翻译遵循 CC BY-SA 4.0 许可协议

http://jsfiddle.net/r8kNL/

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

原文由 Roman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏