jQuery添加一个类 [英] JQuery adding a class
本文介绍了jQuery添加一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在单击<li>
元素时添加一个类.但这没用.这是JQuery代码段
I want add a class when a <li>
element clicked. but it didn't work. Here's JQuery snippet
$(".mama").click(function(){
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$(this).addClass('hi');
}
});
});
和HTML
<ul id="animal">
<li class="mama"><a href="#">cat</a></li>
<li class="mama"><a href="#">dog</a></li>
<li class="mama"><a href="#">Mice</a></li>
</ul>
我也曾尝试通过.map来做到这一点,但没有任何反应.请给出解决方案并进行一些解释.谢谢
i also have tried to do it by .map but nothing happen. please give solution and some explain. Thanks
推荐答案
这应该有效:
$(".mama").click(function(){
var $this = $(this);
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$this.addClass('hi');
}
});
});
因为each
内的this
不是不是 DOM元素<li>
.
because this
inside the each
is not the DOM element <li>
.
这篇关于jQuery添加一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文