开发者

Can't create dropdown box with javascript and jquery

开发者 https://www.devze.com 2023-04-11 10:20 出处:网络
I have the follo开发者_运维知识库wing code: for (i = 0; i < 13; i++){ $(\'.players\').append(\'<div class=\"rule_dropdown\"><select name=\"rule\' + i + \'\">\');

I have the follo开发者_运维知识库wing 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. I expect this to happen:

  1. First for loop add an opening div and select
  2. For each rule in rules array, append an option
  3. Add closing select and closing div
  4. Go back to #1

But this is what actually happens:

  1. First loop add opening AND closing div and select.
  2. Second loop add option with the right content

Does anyone know why?


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>');

}


I think append adds a full element to the DOM rather than just adding the text into the HTML as it were. 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.

The options you want to add should be the child elements of the select, not the div.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号