Javascript 从动态创建的选择元素中选择选项值

Javascript 从动态创建的选择元素中选择选项值,javascript,jquery,html,select,Javascript,Jquery,Html,Select,我想从动态创建的下拉列表中选择一个选项值 下面的代码创建了元素,但是我正在努力使选择生效 var counter = 0; //options will contain a list of document types from the db /* * <option value='1'>one</option> * <option value='2'>two</option> * <option value='3'>thr

我想从动态创建的下拉列表中选择一个选项值

下面的代码创建了元素,但是我正在努力使选择生效

var counter = 0;
//options will contain a list of document types from the db
/*
 *  <option value='1'>one</option>
 *  <option value='2'>two</option>
 *  <option value='3'>three</option>
 */
var $options = $("#listDocumentTypes > option").clone();
$.each(JSON.parse(JSON.stringify(e[2])), function(i, item) {
      var $selectValue = $('<select class="select optionUpdate" id="ddlDocumentTypeID' + counter + '" name="ddlDocumentTypeID[]">').append($options);

        $tr = $('<tr>').append(
        $('<td>').text(item.DocumentLocation.split("/")[item.DocumentLocation.split("/").length - 1]),
        $('<td>').text(ite.FileSize),
        $('<td>').text(item.DocumentDescription),
        $('<td>').html($selectValue.prop('outerHTML')),
        $('<td>').html("<a href='javascript:void(0);' title='delete file' value='" + item.DocumentID + "'  class='btn btn-default txt-color-red deleteFile'><i class='fa fa-trash-o fa-lg'></i></a>"),
      );

      //selection is failing here
      $("#ddlDocumentTypeID" + counter + "").val(item.DocumentTypeID).attr("selected", "selected");
      counter++;
    }

有什么建议吗?

在对象$selectValue上设置值,并附加整个对象,而不仅仅是outerHTML

它没有如图所示工作的原因是您没有将该行添加到dom中,因此在那里搜索它将不会返回任何结果

$.each(JSON.parse(JSON.stringify(e[2])), function (i, item) {

        var $selectValue = $('<select class="select optionUpdate" id="ddlDocumentTypeID'+counter+'" name="ddlDocumentTypeID[]">')
         .append($options); 
         // set value here
         .val(item.DocumentTypeID)


        $tr = $('<tr>').append(
            $('<td>').text(item.DocumentLocation.split("/")[item.DocumentLocation.split("/").length-1]),
            $('<td>').text(ite.FileSize),
            $('<td>').text(item.DocumentDescription),
            // append whole object
            $('<td>').append($selectValue.),
            $('<td>').html("<a href='javascript:void(0);' title='delete file' value='"+item.DocumentID+"'  class='btn btn-default txt-color-red deleteFile'><i class='fa fa-trash-o fa-lg'></i></a>"),


        );


        counter++;
    }
解决了

基本上是在$option上使用array.find并设置selected的属性

 var option =Array.from($options).find(x => x.getAttribute("value") == item.DocumentTypeID);
      option.setAttribute("selected","selected");

您是否正在尝试选择一个甚至还没有添加到DOM中的元素?它不能提供一个可运行的程序来复制问题该演示程序没有做我建议的事情该演示程序是为了展示我所做的事情。我已经更新了它,有你的建议,就像我以前说过的,我已经尝试过了,它会产生相同的结果