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

标签 javascript jquery object

我正在尝试将对象文字传递给 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")

http://jsfiddle.net/j8cXF/

请注意,对于 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/

相关文章:

javascript - 通过 chrome 扩展选项有条件地注入(inject) CSS

javascript - "Syntax error: Invalid or unexpected token"使用 node.js 运行脚本

javascript - 我怎样才能使这个下拉菜单与其父菜单出现在同一行?

javascript - 在 Ace 编辑器中将我的值推到自动完成列表的顶部

javascript - 使用 jQuery 在工具提示中显示表格

JavaScript 是对象或函数

javascript - 使用 d3.js 绑定(bind)数据内的数组(动态生成恒定的 d3.svg.line)

javascript - 德鲁巴 : how to add a JavaScript file in Ctools modal popup

jquery - 输入字段值的长度

JavaScript,没有引用的对象实例