[英]add class to a link having a specific href
I need to add a class if href
attribute is equal to a variable value. 如果
href
属性等于变量值,则需要添加一个类。
In this example the first element should have gold background; 在此示例中,第一个元素应具有金色背景;第二个元素应具有金色背景。
let a = 'a_xp_notes.php'; $('.lmlink[href = ${a}]').addClass('.act');
.lmlink{display:block;} .act{background:gold;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class='lmlink' href='a_xp_notes.php'>NOTES</a> <a class='lmlink' href='a_xp_persons.php'>PERSONS</a> <a class='lmlink' href='a_xp_comps.php'>COMPS</a>
You don't need the dot( .
) in addClass('.act')
您不需要
addClass('.act')
的dot( .
addClass('.act')
Second try with the following example 第二次尝试以下示例
let a = 'a_xp_notes.php'; $(`.lmlink[href='${a}']`).addClass('act');
.lmlink{display:block;} .act{background:gold;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class='lmlink' href='a_xp_notes.php'>NOTES</a> <a class='lmlink' href='a_xp_persons.php'>PERSONS</a> <a class='lmlink' href='a_xp_comps.php'>COMPS</a>
You don't need jquery in this case unless there is a logical evaluation. 在这种情况下,除非有逻辑评估,否则不需要jquery。 You can do the same using only css and it's
href
selector 您可以仅使用CSS及其
href
选择器来执行相同操作
.lmlink { display: block; } a[href="a_xp_notes.php"] { background: gold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class='lmlink' href='a_xp_notes.php'>NOTES</a> <a class='lmlink' href='a_xp_persons.php'>PERSONS</a> <a class='lmlink' href='a_xp_comps.php'>COMPS</a>
用户Javascript 模板字符串 (反引号而不是单引号)
$(`.lmlink[href = ${a}]`).addClass('act');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.