【问题标题】:Element title includes and add class to it [duplicate]元素标题包括并向其添加类[重复]
【发布时间】:2018-12-07 16:45:57
【问题描述】:

如何将类附加到包含特定文本的特定元素,如下所示:

var title = $('.pass-item .title').text();

if(title.includes('7 days within 1')){
   // Here I want to select the element which has the title text '7 days within 1' 
   // And append a class to it
}

希望有人能帮帮我:)

【问题讨论】:

  • $('.pass-item .title').addClass("yourClassName")
  • @Chiller title 将是一个字符串
  • @George,已修复,谢谢我错过了
  • 标题只是className吗?例如:.title,还是tagName?前任。 <title></title>,还是一个属性?例如:<div title="string representing the value of title">

标签: javascript jquery


【解决方案1】:

您可以只搜索那个元素,使用 jQuery 的 :contains,然后使用 addClass 添加类:

$(".pass-item .title:contains('7 days within 1')").addClass("the-class");

如果没有找到也没关系,jQuery的API是set-based,所以不会出错。

【讨论】:

    【解决方案2】:

    但是,您可以检查具有某些类或属性的每个元素,并检查它们是否包含这样的文本:

    $('.title').each(function(){
     if(this.text() == "yabadabadoooo")
     {
      this.addClass("make-me-pretty");
     }
    })
    

    【讨论】:

    • DOM 元素没有addClass 方法; each 回调中的 this 是 DOM 元素,而不是 jQuery 对象。
    • 糟糕,我已经有一段时间没有做这些了。回调中我们不是可以$(this)吗?
    • 是的——但你根本不需要循环。
    【解决方案3】:

    您需要首先获取所有项目的数组,它们映射到该数组并检查每个项目中包含的文本。如果它具有所需的文本,则将其与新类一起返回,否则只需将项目原样返回

    let titles = document.querySelectorAll('.pass-item.title')
    
    titles = Array.prototype.slice.call(titles);
    
    titles.map((item) => { 
        if (item.textContent.includes('7 days within 1')) {
            item.classList.add('new-class')
            return item
        } else {
            return item
        }
    });
    

    https://codepen.io/anon/pen/yEQjZw?editors=1111

    【讨论】:

    • 仅供参考:当您不使用它产生的数组时使用map 不是最佳实践;只需使用forEach。另请注意,在现代浏览器上,来自querySelectorAll 的 NodeList 具有forEach,因此不需要slice(如果需要,可以轻松填充)。 .pass-item .title(在问题中)和.pass-item.title(在上面的答案中)之间也有很大区别。最后,请注意 OP 使用的是 jQuery,这使它成为单行。
    猜你喜欢
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2014-09-14
    • 2018-09-02
    相关资源
    最近更新 更多