我正在动态创建一个元素,我该如何给它一个 id?
_addQuestionElement : function() {
var el = new Element('div');
el.addClass('dg-question-label');
el.set('html', this._getCurrentQuestion().label);
$(this.html.el).adopt(el);
},
我正在使用 moo 工具和 jquery。
非常感谢
最佳答案
你的代码看起来像Mootools,这是我的做法(稍微清理一下你的代码)
_addQuestionElement: function() {
var el = new Element('div', {
'class': 'dg-question-label',
html: this._getCurrentQuestion().label,
id: 'yourId'
});
$(this.html.el).adopt(el);
}
如果您多次生成相同的元素,则您的 id 每次都需要以某种方式保持唯一。
您也可以不使用 el 变量(当然,除非它在您未包含的函数中进一步使用)
_addQuestionElement: function() {
$(this.html.el).adopt(new Element('div', {
'class': 'dg-question-label',
html: this._getCurrentQuestion().label,
id: 'yourId'
}));
}
关于javascript - 动态创建id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846642/