简体   繁体   English

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

[英]How to change sub element of data attribute using jquery

I want to change sub element of below data attribute 我想更改以下数据属性的子元素

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

for this i have added below jquery code but it doesn't work 为此,我添加了下面的jQuery代码,但它不起作用

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

.blue-shape is div class name where i want to change data attribute .blue-shape是我要更改数据属性的div类名称

You can pass a function as a second arguement and you can iterate over to change any value like: 您可以将函数作为第二个论点进行传递,并且可以迭代以更改任何值,例如:

 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> 

jQuery.attr() expects second parameter to be string. jQuery.attr()期望第二个参数为字符串。

have a look at jQuery.data() also 也看看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> 

You need to pass string in 2nd param or you can simply use data() method too like: 您需要在第二个参数中传递字符串,或者也可以像下面这样简单地使用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":""}]'> 

I just updated your jquery with this following code please check and vote if it works 我刚刚使用以下代码更新了您的jquery,请检查并投票是否有效

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

For Reference 以供参考

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM