jQuery重命名所有属性 [英] jquery rename all attributes

查看:90
本文介绍了jQuery重命名所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何使用jQuery更改HTML属性名称?

Possible Duplicate:
How can I change HTML attribute names with jQuery?

我有一个大而复杂的表格,其中包含基于先前选择的问题的不同可用问题.

I have a large/complex form with different available questions based on the previously selected questions.

为使这一点保持井井有条,我有一些重复的输入,都使用相同的名称.这就产生了一个问题,即使隐藏在页面下方的输入也会覆盖可见的输入.

To try and keep this a little organised I have a few duplicate inputs with the same name. This creates the problem where input further down the page even if they are hidden are overwriting the visible inputs.

为避免这种情况,我将所有隐藏的输入都设置为data-name而不是name属性.

To prevent this I have set all hidden inputs with data-name instead of name attribute.

问题 如何更改属性名称.例如:

Questions How can I change the attribute name. E.g:

<input data-name="phone" value="" />
<input data-name="email" value="" />

To
<input name="phone" value="" />
<input name="email" value="" />

推荐答案

鉴于上述HTML标记,我建议:

Given the above HTML mark-up, I'd suggest:

$('input').each(
    function(i,el){
        var data = $(el).data();
        for (datum in data) {
            if (!el[datum]) {
                el[datum] = data[datum];
                el.removeAttribute('data-' + datum);
            }
        }
    });​

JS Fiddle演示.

这使用jQuery data()方法创建一个对象,该对象的数据(如果存在)将附加到要通过each()方法进行迭代的当前jQuery对象.

This uses the jQuery data() method to create an object with the data, if any exists, attached to the current jQuery object being iterated over by the each() method.

有效地,在上面的示例中,if检查当前元素是否尚未具有相同名称的属性(因此,如果name已经存在,则不会被覆盖),以及不存在,请创建该属性/属性.

Effectively, in the above example, the if checks that the current element doesn't already has an attribute of the same name (so the name won't be overwritten if it already exists) and, if it doesn't exist, creates that attribute/property.

要明确覆盖先前存在的属性,请执行以下操作:

To explicitly overwrite a pre-existing attribute:

$('input').each(
    function(i, el) {
        var data = $(el).data();
        for (datum in data) {
            el[datum] = data[datum];
            el.removeAttribute('data-' + datum);
        }
    });​

JS小提琴演示.

参考文献:

这篇关于jQuery重命名所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆