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

标签 javascript jquery

我正在努力……

将显示的数据中的黄色一词替换为红色......

然后...将单词 margin20 添加到 data-shown

然后...将单词 padding20 添加到 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 - 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>

最佳答案

希望是你所需要的

$(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>

关于javascript - 如何在 jQuery 中编辑数据属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250273/

相关文章:

javascript - 一页上有两个计数器

javascript - w3c 验证器忽略 jQuery 和 javascript 更改后的更改

javascript - 在窗口调整大小时更改 div 的位置

javascript - 向页面传递 2 个或更多 URL 参数

jquery - 使用带有数据属性的 JQuery 的驼峰式大小写问题

javascript - 使用 data-option-value 添加类 - Jquery

javascript - 操作 NG-REPEAT 的第一个元素

javascript - AngularJS 在指令标签之间传递 html 内容

javascript - 如何在加载屏幕上更改为上传图片创建的 CSS 圆圈

javascript - 了解 Function.call.bind - 一步一步