我有一个关于重置旧点击元素rel的问题。我已从codepen.io
创建了 DEMO在本演示中,您可以看到有5个按钮。像下面的html代码一样:
<div class="item" id="a1" data-id="1" rel="a">1</div>
<div class="item" id="b1" data-id="1" rel="b">2</div>
<div class="item" id="c1" data-id="1" rel="c">3</div>
<div class="item" id="d1" data-id="1" rel="d">4</div>
<div class="item" id="e1" data-id="1" rel="e">5</div>
当您点击按钮1时,此按钮rel="a"
将更改rel="na"
您可以在开发者控制台中看到它。同样考虑其他按钮(2,3,4,5)
。
现在我需要什么。如果您点击button 2
(点击button 1
后),我想将先前点击的rel="na"
更改为rel="a"
,并将新点击的按钮2 rel="b"
更改为{{1 }}
例如:
首先点击按钮编号1
rel="nb"
此<div class="item" id="a1" data-id="1" rel="a">1</div>
rel为button 1
:
rel="na"
之后单击按钮编号2
<div class="item" id="a1" data-id="1" rel="na">1</div>
此<div class="item" id="b1" data-id="1" rel="b">2</div>
rel与button 2
类似
rel="nb"
同时旧点击<div class="item" id="b1" data-id="1" rel="b">2</div>
rel需要重置
button 1
到
<div class="item" id="a1" data-id="1" rel="na">1</div>
JS
<div class="item" id="a1" data-id="1" rel="a">1</div>
答案 0 :(得分:2)
只需将旧的rel
值存储在jQuery的data()
中,然后将其恢复
$(document).ready(function() {
$(document).on('click', '.item', function() {
var dataid = $(this).attr("data-id");
var rel = $(this).attr("data-rel");
var others = $(this).closest('.buttons').find('.item').not(this);
$(this).data('_rel', rel);
if (['a', 'b', 'c', 'd', 'e'].indexOf(rel) !== -1) {
$('#' + rel + dataid).attr('data-rel', 'n' + rel);
}
others.attr('data-rel', function(_, rel) {
return $(this).data('_rel') || rel;
});
});
});
&#13;
.container {
margin:0px auto;
width:100%;
max-width:550px;
padding:5px;
background-color:#d8dbdf;
position:relative;
overflow:hidden;
margin-top:50px;
border-radius:2px;
-webkit-border-radius:2px;
}
.buttons {
width:100%;
overflow:hidden;
position:relative;
}
.item {
float:left;
padding:10px;
margin-right:5px;
cursor:pointer;
}
.item:nth-child(2n+1){
background-color:red;
color:#ffffff;
border-radius:2px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="buttons">
<div class="item" id="a1" data-id="1" data-rel="a">1</div>
<div class="item" id="b1" data-id="1" data-rel="b">2</div>
<div class="item" id="c1" data-id="1" data-rel="c">3</div>
<div class="item" id="d1" data-id="1" data-rel="d">4</div>
<div class="item" id="e1" data-id="1" data-rel="e">5</div>
</div>
</div>
<div class="container">
<div class="buttons">
<div class="item" id="a2" data-id="2" data-rel="a">1</div>
<div class="item" id="b2" data-id="2" data-rel="b">2</div>
<div class="item" id="c2" data-id="2" data-rel="c">3</div>
<div class="item" id="d2" data-id="2" data-rel="d">4</div>
<div class="item" id="e2" data-id="2" data-rel="e">5</div>
</div>
</div>
&#13;