简体   繁体   中英

How to edit data attribute value in jQuery?

I am trying to…

replace the word yellow with red in data-shown…

then… add the word margin20 to data-shown

then… add the word padding20 to data-shown

then… remove the word tools from data-shown

 $(function() { var data = $(".testclass").attr('data-shown'); data = data.replace('yellow', 'red'); $(".testclass").attr('data-shown', data); alert($(".testclass").attr('data-shown')); }); //alert should read - wh red margin80 padding20 
 [data-shown~="w"] {width: 100px;} [data-shown~="h"] {height: 100px;} [data-shown~="yellow"] {background: yellow;} [data-shown~="red"] {background: red;} [data-shown~="margin80"] {margin: 80px;} [data-shown~="padding20"] {padding: 20px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-shown="wh yellow tools" class="testclass">test</div> 

hope that what you need

 $(function() { var data = $(".testclass").attr('data-shown'); data = data.replace('yellow', 'red'); $(".testclass").attr('data-shown', data); alert($(".testclass").attr('data-shown')); }); 
 [data-shown~="w"] {width: 100px;} [data-shown~="h"] {height: 100px;} [data-shown~="yellow"] {background: yellow;} [data-shown~="red"] {background: red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-shown="wh yellow" class="testclass">test</div> 

I think this is easier to understand:

 $(function () { $('.testclass').addClass('red') alert($('.testclass').attr('class'))//'testclass wh yellow red' $('.testclass').removeClass('yellow') alert($('.testclass').attr('class')) //'testclass wh red' }) 
 .w { width:100px; } .h { height:100px; } .red { background-color:red; } .yellow { background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='testclass wh yellow'>test</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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