如何在jQuery中编辑数据属性值?

时间:2017-07-22 03:10:33

标签: javascript jquery

我想...

在数据显示中用红色替换黄色字......

然后......将margin20添加到数据显示

然后......将padding20添加到数据显示

然后......从数据显示

中删除单词工具



$(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 - w h 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="w h yellow tools" class="testclass">test</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

希望你需要什么

$(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="w h yellow" class="testclass">test</div>

答案 1 :(得分:0)

我认为这更容易理解:

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