【发布时间】:2015-08-23 15:25:59
【问题描述】:
尝试添加和删除类以单击动态按钮,表示此按钮<button class="one"></button> 动态获取类,如下所示:<button class="one text1">text1</button>
因此,如果 按钮一 具有类 .text1 并通过 单击 将此添加类 .hide 到列表项 <li class="text1"> 就像 <li class="text1 show">
按钮二 <button class="two"></button> 和单击添加类 <li class="text2 show">
注意:当单击按钮二时,应删除类.show并添加新类.hide到按钮一。
主 HTML:
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
<a href="#">text1</a>
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
<a href="#">text1</a>
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
<a href="#">text2</a>
</div>
</li>
</ul>
</div>
脚本:
$('.label a').each(function() {
var $this=$(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function(){
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function(){
if(clses.indexOf($(this).attr('class')) === -1){
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if(ind === liInd){
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
我已经尝试通过单击功能添加/删除类,但问题是按钮从列表项中动态获取类,所以我无法定位按钮。
JS/Jquery 对其他方法有什么建议吗?
【问题讨论】:
-
你的问题不够清楚。
-
我的意思是要添加/删除类以通过点击功能列出项目。
-
检查这个DEMO
标签: javascript jquery html addclass removeclass