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 el = $('<div />') .attr('id', myVal);
于 2012-08-07T13:13:58.657 に答える
0

_addQuestionElement、質問要素ごとに一意の ID を生成する必要があると思います。

変数 ID = 0;
var pfx = "id_";

_addQuestionElement : 関数() {
   ...
   el.attr("id", pfx + ++IDs);
于 2012-08-07T13:08:17.800 に答える
0

このように与えることができます。

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

ジャバスクリプトで

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 に答える