2

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

何か案は?

4

2 に答える 2

1

あなたのコードを取り除き、代わりにこれを使用してください:

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

http://jsfiddle.net/j8cXF/

jQuery コンストラクターの場合、以下はすべて同等であり、document.createElement最適化パスをトリガーすることに注意してください。

"<input></input>"
"<input/></input>"
"<input/>"
"<input>"
 // Plus infinite different combinations of whitespace
于 2012-06-02T13:48:54.457 に答える
0

attr()スレッドのタイトルでメソッドについて言及しましたが、使用していません

試す:

 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);
}
于 2012-06-02T13:46:26.187 に答える