【问题标题】:Can't seem to select element based on content似乎无法根据内容选择元素
【发布时间】:2013-02-13 19:00:32
【问题描述】:

我正在尝试根据其内容选择一个元素,但我似乎无法让它工作。

我已经尝试使用带有match() 的正则表达式:

$('.mod')
    .filter(function() {
    return this.match(/abc/);
 })
    .html("Test Worked!")
;  

还有.text()

$('.mod')
    .filter(function() {
    return this.text() == 'abc' ;
 })
    .html("Test Worked")
;

但两者都不起作用。

我做错了吗?我更喜欢使用正则表达式,但现在我只想以某种方式选择元素。

在这里提琴:http://jsfiddle.net/sethj/z3MBw/2/

【问题讨论】:

  • this 指的是元素节点。它没有匹配方法或文本方法。

标签: jquery match


【解决方案1】:

text() 是一个 jQuery 方法:

$('div').filter(function() {
    return $(this).text().match(/mod/);
}).html("Matched!");

FIDDLE

【讨论】:

    【解决方案2】:

    使用这个:

    $('.mod')
      .filter(function() {
      return $(this).text() == 'abc' ;
    })...
    

    您不能在 DOM 元素上调用 text(),您必须将元素包装为 jQuery 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多