如何使用jquery更改数据属性的子元素

时间:2016-07-11 10:07:46

标签: javascript jquery html5 custom-data-attribute html-dataset

我想更改以下数据属性的子元素

<div class="blue-shape"
data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'>

为此我添加了以下jquery代码,但它没有工作

$(document).ready(function(){
    jQuery('.blue-shape').attr("data-actions",{event:'mouseenter', action:'jumptoslide', slide:'rs-16',delay:''});
});

.blue-shape是div类名,我想更改数据属性

4 个答案:

答案 0 :(得分:2)

您可以将函数作为第二个参数传递,您可以迭代以更改任何值,如:

jQuery(document).ready(function($) {
  console.log($('.blue-shape').data('actions'));
  
  $('.blue-shape').attr("data-actions", function() {
    var arr = $(this).data('actions'), newArr = [];
    $.each(arr, function(i, obj){
       if(obj.slide === "rs-18"){
          obj.slide = "rs-16"
       }
       if(i === arr.length-1){ newArr.push(obj); }
    });
    return newArr;
  });
  
  console.log($('.blue-shape').data('actions'));
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue-shape" data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'></div>

答案 1 :(得分:0)

jQuery.attr()期望第二个参数为字符串。

查看jQuery.data()

$('document').ready(function() {
  jQuery('.blue-shape')
    .attr("data-actions", "{event:'mouseenter', action:'jumptoslide', slide:'rs-16',delay:''}");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue-shape" data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'>DATA</div>

答案 2 :(得分:0)

您需要在第二个参数中传递字符串,或者您只需使用data()方法:

console.log($('.blue-shape').data("actions"));
$('.blue-shape').data("actions","[{event:'mouseenter', action:'jumptoslide', slide:'rs-16',delay:''}]");
console.log($('.blue-shape').data("actions"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="blue-shape"
data-actions='[{"event":"mouseenter","action":"jumptoslide","slide":"rs-18","delay":""}]'>

答案 3 :(得分:0)

我刚用以下代码更新了您的jquery,请检查并投票是否有效

$('document').ready(function(){
jQuery('.blue-shape').attr("data-actions","[{'event':'mouseenter', 'action':'jumptoslide', 'slide':'rs-16','delay':''}]");
});

供参考

https://jsfiddle.net/jasonantho/6ehmded3/