Jquery 在数组中除此元素外的所有元素上设置数据属性
这是我的标记Jquery 在数组中除此元素外的所有元素上设置数据属性,jquery,html,this,Jquery,Html,This,这是我的标记 <div class="parent"> <img data-position="1" src=""> <img data-position="2" src=""> <img data-position="3" src=""> <img data-position="4" src=""> </div> 这段代码在第一次运行正常,但在第二次单击时,我得到了不同的结果 您可以按原来显示的那样执行而
<div class="parent">
<img data-position="1" src="">
<img data-position="2" src="">
<img data-position="3" src="">
<img data-position="4" src="">
</div>
这段代码在第一次运行正常,但在第二次单击时,我得到了不同的结果 您可以按原来显示的那样执行而不是(此)
,然后更新它们上的数据位置。然后在某个点将单击的数据位置更新为1
var$images=$('img')。在('click',function()上{
$images.not(this).attr('data-position',函数(index){
收益率指数+2;
});
$(this.attr('data-position',1);
});代码>
看看这把小提琴:
以下是重要的代码:
var imgs = $('div.parent > img')
imgs.on('click', function(index) {
$(this).attr("data-position", "1");
var otherElements = imgs.not(this);
otherElements.each(function(index) {
$(this).attr("data-position", index+2);
})
// Optionally, uncomment the next 3 lines to output the data-positions
//$(imgs).each(function(index) {
// console.log(index, $(this).attr("data-position"));
//});
});
我的解决方案包括在父级上设置事件侦听器,以便更容易查询和操作其子级。单击目标之前的元素将“换行”,并从数组中最后一个元素的左边继续编号
const $parent = $('.parent');
const $children = $parent.children();
const childrenLength = $children.length;
$parent.on('click', e => {
const clickedIndex = $children.index(e.target);
let rearange = 1;
$children.each((i, el) => {
if (i < clickedIndex) {
el.dataset.position = (childrenLength - clickedIndex + 1) + i;
} else {
el.dataset.position = rearange++;
}
});
});
const$parent=$('.parent');
const$children=$parent.children();
const childrenLength=$children.length;
$parent.on('click',e=>{
常量clickedIndex=$children.index(e.target);
设重新量程=1;
$children.每个((i,el)=>{
如果(i
运行示例:我看不出您在哪里对数据位置
值进行赋值。你只是在循环。你想对所有内容重新编号,还是只需将当前的数字1交换为单击的内容就足够了。循环时,我第一次得到3(这是正确的),然后如果我再单击一次,我得到2,这是不正确的。@Taplar,是的,我需要对所有内容重新编号。这些数字需要换行吗?比如,第一个元素将获得数据位置=4的第一次单击是否在别处?
const $parent = $('.parent');
const $children = $parent.children();
const childrenLength = $children.length;
$parent.on('click', e => {
const clickedIndex = $children.index(e.target);
let rearange = 1;
$children.each((i, el) => {
if (i < clickedIndex) {
el.dataset.position = (childrenLength - clickedIndex + 1) + i;
} else {
el.dataset.position = rearange++;
}
});
});