我想更改以下数据属性的子元素
<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类名,我想更改数据属性
答案 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()
期望第二个参数为字符串。
$('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':''}]");
});
供参考