如何在Javascript中为特定属性赋值

时间:2015-08-14 03:35:28

标签: javascript

我正在实现一个扩展表单函数,我需要增加某些属性,包括像data-display="#display_student_1_gender"这样的属性。

找到属性没有问题但是当我尝试重命名时它失败(标记如下)。是什么给了什么?

Javascript:

<script>
var counter = 0;
function moreFields(val1, val2, val3) {
    counter++;
    var newField = document.getElementById(val1).cloneNode(true);
    newField.id = '';
    newField.style.display = 'block';
    var newFields = newField.querySelectorAll('[name], [id], [for], [data-display]');
        for (var i=0;i<newFields.length;i++) {
            var theNames = newFields[i].name
            if (theNames)
                newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
            var theNames2 = newFields[i].id;
            if (theNames2)
                newFields[i].id = theNames2 + counter;
            var theNames3 = newFields[i].htmlFor;
            if (theNames3)
                newFields[i].htmlFor = theNames3 + counter;
            var theNames4 = newFields[i].attr('data-display'); //line 14 Error
            if (theNames4)
                newFields[i].attr('data-display') = theNames4 + counter;    
        }           
    var insertHere = document.getElementById(val2);
    insertHere.parentNode.insertBefore(newField,insertHere);
}
</script>

1 个答案:

答案 0 :(得分:1)

你正在处理dom元素(newFields[i])引用,它不像attr()这样的方法(我认为你从一些jQuery引用中获取 - 但是因为你没有用jQuery标记这个问题,我假设你没有使用它)。

您需要使用getAttribute()和setAttribute()来获取/设置属性值

var theNames4 = newFields[i].getAttribute('data-display');
newFields[i].setAttribute('data-display', theNames4 + counter)

或者如果您使用数据api

var theNames4 = newFields[i].dataset.display;
newFields[i].dataset.display = theNames4 + counter