【问题标题】:dynamic select dropdown - no selected option动态选择下拉菜单 - 没有选择的选项
【发布时间】:2015-10-21 11:43:03
【问题描述】:

我正在尝试创建一个动态选择;

每次我在数据库表上创建一个用户时,它都会在标记中添加一个<td class="users"><td class="users">name of the user extracted from the db</td>

html

<select id="selectUser">
  <option selected disabled>Select a user...</option>
</select>

js

var names = {};
$('.users').each(function() {  
     names = $(this).html();
     printContent(names);
});

function printContent(content)
{
   $( '<option class="selectOption">' + content + '</option>' ).appendTo( "#selectUser" );

}

它确实会根据需要显示用户名,但是,选择不会更改所选类。如何将选定的类添加到正在显示的元素中?

我已经在http://jsfiddle.net/hh7r7p3w/ 中添加了代码。顺便提一下,带有用户名的真实数据来自数据库,所以这个名字可以变化。

我是否正在尝试以我尝试的方式做一些我无法做到的事情?

谢谢

【问题讨论】:

标签: jquery select dropdown


【解决方案1】:

您可以将选项的属性添加为

$(document).ready(function() {

  var names = {};
  $('.users').each(function() {
    names = $(this).html();
    printContent(names);
  });

  function printContent(content) {
    $('option:selected').prop('selected', false);
    $('<option class="selectOption">' + content + '</option>').appendTo("#selectUser");
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="users">User 1</td>
    <td class="users">User 2</td>
    <td class="users">User 3</td>
    <td class="users">User 4</td>
    <td class="users">User 5</td>
  </tr>
</table>

<select id="selectUser">
  <option selected disabled>Select a user...</option>
</select>

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2018-02-17
    相关资源
    最近更新 更多