简体   繁体   English

无法使用javascript和jquery创建下拉框

[英]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: 我希望这会发生:

  1. First for loop add an opening div and select 首先为循环添加一个开头的div并选择
  2. For each rule in rules array, append an option 对于规则数组中的每个规则,附加一个选项
  3. Add closing select and closing div 添加关闭选择和关闭div
  4. Go back to #1 回到第一

But this is what actually happens: 但这是实际发生的情况:

  1. First loop add opening AND closing div and select. 第一个循环添加开始和结束div并选择。
  2. Second loop add option with the right content 内容正确的第二个循环添加选项

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM