jQuery:为每个点击函数添加多个数据属性

jQuery: add multiple data attributes with each click function

本文关键字:函数 添加 数据属性 jQuery      更新时间:2023-09-26

我有一个点击功能设置,当你点击.clickdiv时,它会获取data-hook属性,并将其作为data-filter属性添加到.buttondiv,这很好,但每次点击后,它都会用新属性替换data-filter属性,理想情况下,我希望每次点击都给属性添加一个新值,用逗号分隔每个值
以下是jsFiddle演示:http://jsfiddle.net/neal_fletcher/pSZ2G/

HTML

<div class="button">THIS</div>
<div class="click" data-hook="one">CLICK</div>
<div class="click" data-hook="two">CLICK</div>
<div class="click" data-hook="three">CLICK</div>
<div class="click" data-hook="four">CLICK</div>
<div class="click" data-hook="five">CLICK</div>

jQuery:

$(".click").click(function () {
    var thing = $(this).attr("data-hook");
    $('.button').attr('data-filter', thing);
});

如果这是可能的话?如有任何建议,我们将不胜感激!

您可以存储以前的值,也可以与新单击的值进行连接,类似于。

$(".click").click(function () {
    var thing = $(this).attr("data-hook");
    var earData = $('.button').attr('data-filter');
    if(typeof earData != 'undefined'){
        $('.button').attr('data-filter', earData + ","+thing);
    }else{
        $('.button').attr('data-filter', thing);
    }
});

DEMO

$(".click").click(function () {
   var thing = $(this).attr("data-hook");
   var prevValue = $('.button').attr('data-filter');
   if(prevValue){
       $('.button').attr('data-filter', prevValue +','+thing)
   }
   else{
       $('.button').attr('data-filter', thing)
   }

});

$(".click").click(function () {
    var thing = $(this).attr("data-hook")||'';
    var df = $('.button').attr('data-filter')||'';
    $('.button').attr('data-filter', df+','+thing)
});

顺便说一句。。我希望你没有任何其他元素包含.button类。如果你想更新一个目标,你应该通过id attrib引用。