我正在尝试将对象文字传递给 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);
}
有什么想法吗?
最佳答案
摆脱您的代码并改用它:
$( "<input>", {type:'text', id:'inputBox'} ).appendTo("#divAppendTo")
请注意,对于 jQuery 构造函数,以下所有内容都是等效的并触发 document.createElement
优化路径:
"<input></input>"
"<input/></input>"
"<input/>"
"<input>"
// Plus infinite different combinations of whitespace
关于javascript - 在 jQuery 中将对象传递给 .attr(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10862705/