0

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

非常感谢

4

8 回答 8

2

您的代码看起来像 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'
    }));
}​
于 2012-08-07T13:12:03.373 回答
1

只需通过以下方式分配 id(如果您使用 new Element() 创建了元素):

var yourCustomId = "myId";
el.id = yourCustomId;

或者使用 Mootools 属性设置功能:

var yourCustomId = "myId";
el.setProperty("id", yourCustomId);
于 2012-08-07T13:04:13.033 回答
0

你可以这样给

var uniqueNumber = 1; //define uniqueNumber globally and increament at each element creation

使用 javascript

el.id = 'idprefix' + uniqueNumber++)

使用 jQuery

$(el).attr('id','idprefix' + uniqueNumber++);
于 2012-08-07T13:04:06.787 回答
0

在 jQuery 中,要创建一个带有 ID 的 div,您可以执行以下操作:

function createDiv(id) {
    $("body").append("<div id=" + id + "></div>");
}

createDiv("myNewDivId");
于 2012-08-07T13:05:41.220 回答
0

_addQuestionElement,我认为您需要为每个问题元素生成一个唯一的 id。

变量 ID = 0;
var pfx = "id_";

_addQuestionElement:函数(){
   ...
   el.attr("id", pfx + ++IDs);
于 2012-08-07T13:08:17.800 回答
0
var el = $('<div />') .attr('id', myVal);
于 2012-08-07T13:13:58.657 回答
0

无论如何, MooTools 创建或访问的所有元素都会自动获得一个唯一的uid(对于 DOM),从而使您不必自己保持状态(如果您想自动执行此操作)。

console.log( Slick.uidOf( new Element('div') ) )

所以...

_addQuestionElement: function() {
    var el = new Element('div.dg-question-label', {
        html:  this._getCurrentQuestion().label
    });

    // prefix number with uid-
    el.set('id', 'uid' + Slick.uidOf(el)).inject(this.html.el);    
},

通过组合元素构造函数给它一个 id,它是:

var el = new Element('div#someid.dg-question-label')或将其添加到传递给构造函数的属性中:

new Element('div', { id: 'foo' })

于 2012-08-07T15:34:08.380 回答
0

您可以使用 jQuery 插件idfy

完全披露:我写了那个插件:)

于 2013-07-14T15:54:17.143 回答