为数组中除此元素之外的所有元素设置数据属性

Set data attribute on all elements in array but this element

这是我的标记

<div class="parent">
  <img data-position="1" src="">
  <img data-position="2" src="">
  <img data-position="3" src="">
  <img data-position="4" src="">
</div>

当单击任何 img 元素时,单击的元素需要将其 data-position 设置为 1,其余元素应跟随 data-position="2" 和很快。为此,我不能附加或重新排列元素,因为这没有任何效果。

这是我试过的。我想,为什么不让所有 not(this) 元素通过循环并分配数据属性。

var img = $('img')
img.on('click', function() {
    var otherElements = img.not(this).length;
    console.log(otherElements)
});

这段代码第一次运行正确,但第二次我得到了不同的结果。

您可以按照最初显示的方式执行 not(this),然后更新它们的数据位置。然后在某个时候将点击的数据位置更新为 1。

var $images = $('img').on('click', function(){
  $images.not(this).attr('data-position', function(index){
    return index + 2;
  });
  
  $(this).attr('data-position', 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <img data-position="1" src="" alt="one">
  <img data-position="2" src="" alt="two">
  <img data-position="3" src="" alt="three">
  <img data-position="4" src="" alt="four">
</div>

看看这个 fiddle:https://jsfiddle.net/yam1hox6/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"));
    //});
});

我的解决方案包括在父项上设置事件侦听器,以便更容易查询和操作其子项。单击目标之前的元素将 'wrap' 并从数组中最后一个元素左侧的位置继续编号。

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++;
    }
  });
});

运行 示例:jsfiddle