简体   繁体   English

当链接具有特定标签时如何添加类

[英]How to add a class when a link has a certain label

I have a series of links with no a classes. 我有一系列的没有联系a班级。 I am unable to manually add any classes in the HTML...otherwise I would. 我无法在HTML中手动添加任何类...否则,我会这样做。 I want to use either JavaScript or jQuery to detect a certain link label and add a class to it if the match is found. 我想使用JavaScript或jQuery来检测某个链接标签,并在找到匹配项的情况下向其添加一个类。

Here is the HTML: 这是HTML:

<ul class="menu-main-nav">
   <li><a href="/destination/">Duck</a></li>
   <li><a href="/destination/">Duck</a></li>
   <li><a href="/destination/">Goose</a></li>
</ul>

I want to add a class whenever "Goose" appears. 每当“鹅”出现时,我都想添加一个类。 Here is what I attempted...and failed. 这是我尝试过的...失败了。

$(document).ready(function(){
    if ($("#menu-main-nav li a").text() == "Goose") { this.addClass("itsagoose")};
});

Use the .filter method: 使用.filter方法:

$("#menu-main-nav li a").filter(function(){
    return $(this).text() == "Goose"; //<--- Only include these elements
}).addClass("itsagoose");

Use .html() instead of .text() if you want an exact match, and don't want to allow anything else (eg, don't match <a><span>Goose</span></a> ). 如果您想要完全匹配,并且不想允许其他任何内容(例如,不匹配<a><span>Goose</span></a> ),请使用.html()而不是.text() )。 。

Fiddle: http://jsfiddle.net/RWSCY/ 小提琴: http//jsfiddle.net/RWSCY/

Look at the jQuery contains selector . 看一下jQuery包含选择器 That's what it's for :) 这就是它的目的:)

Well, you could use filter: 好吧,您可以使用过滤器:

Demo 演示版

$("a").filter(function(){
    return $(this).text() == "Goose"
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM