javascript - 动态创建id

标签 javascript jquery mootools

我正在动态创建一个元素,我该如何给它一个 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/

相关文章:

jquery - 如果没有选择单选按钮,有更好的 jQuery 代码来选择单选按钮吗?

javascript - MooTools 和 JQuery 并排

javascript - 如何使用 MooTools 和 Request.HTML 从远程页面抓取元素?

javascript - 如何防止点击提交按钮时页面刷新

javascript - Jquery:获取页面的所有html源但排除一些#ids

javascript - 将隐藏字段传递给 JavaScript 函数

javascript - jQuery 无法在内联网站点上运行

javascript - 取消订阅事件监听器 react Hook

javascript - 数据未显示在流程图中(metronic 主题)

javascript - 日期选择器未出现