我怎样才能改变;这";使用javascript的类名?
我有一个包含所有拉丁字母的按钮列表,我想将类名从“m_字母”更改为“m_字母活动”,例如,这样我就可以切换它们 我的javascript代码如下我怎样才能改变;这";使用javascript的类名?,javascript,jquery,class,dom,Javascript,Jquery,Class,Dom,我有一个包含所有拉丁字母的按钮列表,我想将类名从“m_字母”更改为“m_字母活动”,例如,这样我就可以切换它们 我的javascript代码如下 $(".m_letter").click(function(){ $(this).className = "m_letter active"; //This is an example i tried other codes that i found on net. }); Html A B C ... Z 使用 这将在单击时添加类: $(".m
$(".m_letter").click(function(){
$(this).className = "m_letter active"; //This is an example i tried other codes that i found on net.
});
Html
A
B
C
...
Z
使用
这将在单击时添加类:
$(".m_letter").click(function(){ $(this).addClass('active'); });
如果需要先从其他m_字母中删除活动类,请添加此行
$('.m_letter.active').removeClass('active')
使用.addClass()
因为您使用的是jQuery,所以很容易:
$(this).addClass('active');
在单击处理程序中
不要使用:
$('.m_letter').addClass('active');
因为这会将所有项目设置为活动状态。我想您要查找的是: JS
$(".m_letter").click(function(){
$(".m_letter").removeClass("active");
$(this).addClass( "active" );
});
你把两种不同的方法混为一谈了。一个是本机API,它将是
this.className=…
,另一个是jQuery API,要使用它,必须构造一个jQuery对象来包装this
元素,并执行$(this).addClass(…
,其中.addClass()
是从$
函数返回的jQuery对象上的一个方法。我尝试了它,它工作了,但是addClass('active')和addClass('m_-letter-active')之间有什么区别,因为我认为两者都有相同的结果。@不知道相同的结果,但第二个结果很详细。添加实际添加的类就足够了。
$('.m_letter').addClass('active');
$(".m_letter").click(function(){
$(".m_letter").removeClass("active");
$(this).addClass( "active" );
});