Jquery: 如何使用函数.attr()动态添加属性

3
我需要动态地添加属性到输入框,但是它并不起作用。
- this.nomRoot 是组件名称,这里是 'input'。 - this.lstAttr 是一个包含属性(例如'name'或'checked')的数组。 - this.lstAttrValue 是一个包含属性值(例如'myCheckbox'或'true')的数组。
以下是我的代码:
Component("Input", {
    add: function(element, type) {
       html = $('<'+this.nomRoot+' type="'+ type +'" />').appendTo('#'+element);

       for(key in this.lstAttr) {
          alert(this.lstAttr[key]);
          alert(this.lstAttrValue[key]);
          $(html).attr("'"+this.lstAttr[key]+"', '"+this.lstAttrValue[key]+"'");
       }

    }
});

我的代码在Firebug中可以运行,但没有添加属性。

我尝试了像这样的东西:

  • this.lstOptions was an array with the attributs and attributs values like "name, myCheckbox"

    $("<"+this.nomRoot+" />").attr(this.lstOptions).appendTo(element);
    
1个回答

3
您想设置属性和值,只需引用两个索引即可,无需构建某种字符串。
$(html).attr(this.lstAttr[key], this.lstAttrValue[key]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接