javascript - 删除并存储多个属性

标签 javascript jquery

我有隐藏的输入,可以从某些池/组中删除徽章。

<input type="hidden" name="Remove[<?= $i; ?>][Badge][id]" value="<?= $badge['id']; ?>" data-id="<?= $badge['id']; ?>" />

我对 JS 和 JQuery 比较陌生,但这是我到目前为止所掌握的......

$('.glyphicon-remove').click(function(){
        $(this).parent().toggleClass('remove');
        $(this).siblings().removeAttr("name value data-id");
        return false;
    }); 

问题是当他们点击 .glyphicon-remove 时,我需要它来切换这些属性。我还尝试了 JQ 函数 detach,但无法将其与 attr() 标记一起使用。

我需要能够在每次点击时切换这些属性。如果您有任何建议或者我是否可以澄清我的问题,请告诉我。

最佳答案

您需要某种toggleAttr来保持旧值恢复。 请尝试以下操作:

$('.glyphicon-remove').click(function(){
    $(this).parent().toggleClass('remove');
    var sib = $(this).siblings();
    if ($(this).parent().hasClass('remove')) {
        //Stores attrs to correspontent data-* attribute
        sib.each(function(){
           $(this).data("name", $(this).attr("name"));
           $(this).data("value", $(this).attr("value"));
           $(this).data("data-id", $(this).attr("data-id"));
        });
        sib.removeAttr("name value data-id");
    } else {
        //Restores attrs from the correspondent data-* attribute
        sib.each(function(){
           $(this).attr("name", $(this).data("name"));
           $(this).attr("value", $(this).data("value"));
           $(this).attr("data-id", $(this).data("data-id"));
        });
        sib.removeData("name");
        sib.removeData("value");
        sib.removeData("data-id");
    }
    return false;
});

关于javascript - 删除并存储多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535589/

相关文章:

javascript - 同时显示不同 div 中选定复选框的值并求和

javascript - 如何在触发 jQuery 动画之前打开链接

javascript - Aurelia 导航时没有 'refresh' vm

javascript - 与 Axios react : Questionn with its choices in the same page

javascript - Angularjs 不发布隐藏值

Jquery:.preventDefault() 并返回 false 不起作用

javascript - 从对象的 JavaScript 数组创建树结构

javascript - 使用带有条件javascript的 map 从数组中提取id

javascript - javascript中的正则表达式获取以特定字符串开头的数组的所有字段

javascript - 调整浏览器全页 js 大小时消除延迟