我在表格中有一系列<td>
个元素,在我的上下文中,是&#34; slot&#34;用户可以选择的空间。每个插槽都有一个属性(data-slot-stamp
),用于保存插槽的ID(时间戳)。当用户点击广告位时,该时间戳会添加到其他元素的.addButton
)属性data-selected-slots
中。如果用户再次点击该广告位,则该广告位将从.addButton
的data-selected-slots属性中删除。
以下代码段正在运行,但第一次点击除非用户正在从他们的选择中删除该插槽。
所需行为的示例:
在我的案例中发生了什么:
Html结构:
<table class="spacesTable">
<tr>
<td class="slot used unselected" data-slot-stamp="123456789">
Slot 1
</td>
<td class="slot used unselected" data-slot-stamp="987654321">
Slot 2
</td>
<td class="slot used unselected" data-slot-stamp="654321987">
Slot 3
</td>
<td>
<div class="addButton" data-selected-slots="">
Add Button
</div>
</td>
</tr>
</table>
相关的jQuery:
$('.spacesTable').on('click', '.slot.used', function() {
var curAtts = $(this).siblings('.addButton').attr('data-selected-slots');
var clickedStamp = $(this).attr('data-slot-stamp');
if ($(this).hasClass('unselected')) {
$(this).addClass('selected').removeClass('unselected');
//Add to the values stored in the data-selected-slots attr of the button for this row
var spacer = ',';
if (!curAtts) {
curAtts = '';
spacer = '';
}
$(this).siblings('.addButton').attr('data-selected-slots', clickedStamp+spacer+curAtts);
} else if ($(this).hasClass('selected')) {
$(this).removeClass('selected').addClass('unselected');
//check to see if the slot timestamp is in the button's data-selected-slots attr, and if so, remove it
var findStamp = curAtts.indexOf(clickedStamp);
if (findStamp != -1) {
curAtts = curAtts.replace(clickedStamp+',','');
$(this).siblings('.addButton').attr('data-selected-slots', curAtts);
}
}
});
答案 0 :(得分:0)
因为&#34;,&#34;
改变这个:
curAtts = curAtts.replace(clickedStamp+',','');
有类似的东西:
if (curAtts.indexof(",") > 0) {
curAtts = curAtts.replace(clickedStamp+',','');
}else{
curAtts = curAtts.replace(clickedStamp,'');
}
希望有所帮助