【问题标题】:How to target a <th> which contains only specific text?如何定位仅包含特定文本的 <th>?
【发布时间】:2017-07-24 17:53:58
【问题描述】:

我正在运行它并且它有效:

$wikiDOM.find(".infobox th:contains('Date')")

但是,这也可能是Date of birth,而我只需要使用字符串Date 来定位那些onse。

更新

完整案例:

if ($wikiDOM.find(".infobox th:contains('Location')").length > 0 && $wikiDOM.find(".infobox th:contains('Date')").length > 0) {
  $('#results').append('<li>' + curTitle + "<br>" + $wikiDOM.find('.infobox th:contains("Location")').siblings('td').text() + '<br>' + $wikiDOM.find('.infobox th:contains("Date")').siblings('td').text() + '</li>');
}

试过了:

$.fn.textEquals = function(txt) {
  return $(this).text() == txt;
}
if ($wikiDOM.find(".infobox th").textEquals('Location') && $wikiDOM.find(".infobox th").textEquals('Date')) {
  $('#results').append('<li>' + curTitle + "<br>" + $wikiDOM.find('.infobox th:contains("Location")').siblings('td').text() + '<br>' + $wikiDOM.find('.infobox th:contains("Date")').siblings('td').text() + '</li>');
}

【问题讨论】:

  • 分享你的代码
  • 使用$wikiDOM.find('.infobox th').filter(...) 和一些适合检查文本内容的过滤功能。
  • @Bhargav 关于这个问题没有什么要补充的了,但是我相信我在这里找到了答案stackoverflow.com/a/2447117/7790433
  • @Bhargav 更新完整代码

标签: javascript jquery


【解决方案1】:

您可以使用JQuery's filter 方法:

$(".infobox th").filter(function() {
  return $(this).text() === "Date";
})

您的代码可以重构为类似(未测试):

function doSelect(text) {
    return $wikiDOM(".infobox th").filter(function() {
        return $(this).text() === text;
    })
}

if (doSelect('Location').length > 0 && doSelect('Date').length > 0) {
  $('#results').append('<li>' + curTitle + "<br>" + doSelect("Location").siblings('td').text() + '<br>' + doSelect("Date").siblings('td').text() + '</li>');
}

【讨论】:

    【解决方案2】:

    HTML

    <table>
    <thead>
    <tr>
      <th>test1</th>
      <th>test2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
    
        </td>
        <td>
    
        </td>
      </tr>
    </tbody>
    </table>
    

    这是你的 jquery

    //I have tested below line and it worked
    //$('th:contains("test1")').css('color', 'red') 
    
    var myth = $('th:contains("test1")'); //here is your th
    

    【讨论】:

    • 是的,就像我的问题一样,文本是 test1 和 test2 不仅是 test
    【解决方案3】:

    您可以使用 .text() 返回元素的字符串值并像这样运行条件:

    HTML 示例:

    <th>My Text</th>
    <th>My other Text</th>
    

    jquery 示例:

    $('th').each(function()
    {
        if ($(this).text() === 'My Text') {
            //do something
        }
    })
    

    这将遍历所有元素,然后对文本值运行 if 语句。可以在此处找到每个功能的信息:

    http://api.jquery.com/jQuery.each/

    http://api.jquery.com/text/

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多