在jQuery中将对象传递给.attr()

时间:2022-06-29 20:35:27

I am trying to pass an object literal to the .attr() method in jQuery to automate creating a DOM element. The problem is when there is more than one attribute to set it fails.

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

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);
}

Any ideas?

2 个解决方案

#1


1  

Get rid of your code and use this instead:

摆脱你的代码并使用它代替:

$( "<input>", {type:'text', id:'inputBox'} ).appendTo("#divAppendTo")

http://jsfiddle.net/j8cXF/

Note that for jQuery constructor all the following are equivalent and trigger the document.createElement optimization path:

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

"<input></input>"
"<input/></input>"
"<input/>"
"<input>"
 // Plus infinite different combinations of whitespace

#2


0  

You mentioned attr() method in thread title , but aren't using it

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

Try:

 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);
}

#1


1  

Get rid of your code and use this instead:

摆脱你的代码并使用它代替:

$( "<input>", {type:'text', id:'inputBox'} ).appendTo("#divAppendTo")

http://jsfiddle.net/j8cXF/

Note that for jQuery constructor all the following are equivalent and trigger the document.createElement optimization path:

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

"<input></input>"
"<input/></input>"
"<input/>"
"<input>"
 // Plus infinite different combinations of whitespace

#2


0  

You mentioned attr() method in thread title , but aren't using it

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

Try:

 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);
}