首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将对象传递给jQuery中的.attr()

问将对象传递给jQuery中的.attr()
EN

Stack Overflow用户
提问于 2012-06-02 21:34:50
回答 2查看 1.2K关注 0票数 2

我正在尝试将对象文字传递给jQuery中的.attr()方法,以自动创建一个DOM元素。问题是当有多个属性要设置时,它会失败。

代码语言:javascript
复制
var atts = {'type':'text', 'id':'#inputBox'};
createElem('<input></input>', '#divToAppendTo', atts);


function createElem(typeOfField, fldToAppendTo, atts){
    // this works when there is only one attribute to set, but fails when there is more than 1
    jQuery(typeOfField, atts).appendTo(fldToAppendTo);
}

有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2012-06-02 21:48:54

去掉你的代码,使用下面的代码:

代码语言:javascript
复制
$( "<input>", {type:'text', id:'inputBox'} ).appendTo("#divAppendTo")

http://jsfiddle.net/j8cXF/

请注意,对于jQuery构造函数,以下所有条件都是等效的,并触发document.createElement优化路径:

代码语言:javascript
复制
"<input></input>"
"<input/></input>"
"<input/>"
"<input>"
 // Plus infinite different combinations of whitespace
票数 1
EN

Stack Overflow用户

发布于 2012-06-02 21:46:26

您在线程标题中提到了attr()方法,但没有使用它

尝试:

代码语言:javascript
复制
 function createElem(typeOfField, fldToAppendTo, atts){
     // this works when there is only one attribute to set, but fails when there is more than 1
     jQuery(typeOfField).attr( atts).appendTo(fldToAppendTo);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10862705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档