[英]Can't create dropdown box with javascript and jquery
I have the following code: 我有以下代码:
for (i = 0; i < 13; i++){
$('.players').append('<div class="rule_dropdown"><select name="rule' + i + '">');
for(j = 0; j < rules.length; j++){
$('.players').append('<option>' + rules[j] + '</option>');
}
$('.players').append('</select></div>');
}
I want to have 13 dropdown lists with the same content. 我想拥有13个内容相同的下拉列表。 I expect this to happen:
我希望这会发生:
But this is what actually happens: 但这是实际发生的情况:
Does anyone know why? 有人知道为什么吗?
I think append
adds a full element to the DOM rather than just adding the text into the HTML as it were. 我认为
append
将一个完整的元素添加到DOM中,而不仅仅是将文本添加到HTML中。 Try building up your elements individually and adding them a bit like this: 尝试分别构建您的元素并添加如下所示的元素:
for (i = 0; i < 13; i++){
var $select = $('<select name="rule' + i + '"></select>');
for(j = 0; j < rules.length; j++) {
$select.append('<option>' + rules[j] + '</option>');
}
var $div = '<div class="rule_dropdown"></div>';
$div.append($select);
$('.players').append($div);
}
From the documentation: 从文档中:
The .append() method inserts the specified content as the last child of each element in the jQuery collection.
.append()方法将指定的内容作为jQuery集合中每个元素的最后一个子元素插入。
The options you want to add should be the child elements of the select, not the div. 您要添加的选项应该是select的子元素,而不是div。
I think this is what you want to do.. 我想这就是你想做的。
var rules=[1,2,3,4,5,6];
for (i = 0; i < 13; i++){
$('.players').append('<div class="rule_dropdown"><select id="rule'+ i +'" name="rule' + i + '">');
for(j = 0; j < rules.length; j++){
$('#rule'+i).append('<option>' + rules[j] + '</option>');
}
$('.players').append('</select></div>');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.