【问题标题】:jquery selector - Select value not inside another nested tagjquery选择器 - 选择不在另一个嵌套标签内的值
【发布时间】:2010-12-16 03:14:08
【问题描述】:

是否可以选择不在另一个嵌套标签内的标签的值?

例如在下面的代码中,我想从 $('#example') 中获取“我想选择的文本”。

<td id="example">
    <a> Text I don't want to select</a>
    <span> Other text I don't want to select</span>
    Text I want to select
    <anyOtherTag> Other text I don't want to select</anyOtherTag>
</td>

谢谢。

【问题讨论】:

标签: javascript jquery html jquery-selectors


【解决方案1】:

您可以使用.contents().filter() 直至文本节点类型(nodeType == 3),如下所示:

var text = $("#example").contents().filter(function() { 
              return this.nodeType == 3; 
           }).text();
alert($.trim(text));

You can try it out here。因为.text() 获取所有文本节点,包括其他空格,所以您可能想要$.trim()(因为IEString.trim())我上面的结果。

【讨论】:

  • 谢谢好主意。唯一的问题是我无法在我的真实示例中使用它。实际上,我的表与 jquery 插件数据表和 jeditable 一起使用,因此当用户单击表时,我想获取该信息。我已经记录了我的变量,并且使用 $(this) 得到了正确的 td,但是当我执行 $(this).contents() 时它是空的。可能是因为我正在使用数据表插件?
  • @Javi - 这一切都取决于你的上下文,试试console.log(this) 看看你在什么时候发生
猜你喜欢
  • 1970-01-01
  • 2010-11-14
  • 2017-02-21
  • 2017-05-04
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多