javascript - 无法使用 jquery 设置选择的选定值

标签 javascript jquery html html-select

这是我的html代码

<select id="ddlCountry" placeholder="optional" class="select" title="Select Country">
 <option value="0">Select Country</option>
</select>

这是 jquery 代码......

$(document).ready(function () {

  $('select.select').each(function () {
    var title = $(this).attr('title');
    if ($('option:selected', this).val() != '') {
      title = $('option:selected', this).text();
      $(this)
        .css({
          'z-index': 10,
          'opacity': 0,
          '-khtml-appearance': 'none'
        })
        .after('<span class="select">' + title + '</span>')
        .change(function () {
          val = $('option:selected', this).text();
          $(this).next().text(val);
        })
    }
  });


  var country = [{
    "CountryID": 1,
    "CountryName": "Afghanistan"
  }, {
    "CountryID": 2,
    "CountryName": "Albania"
  }, {
    "CountryID": 3,
    "CountryName": "Algeria"
  }, {
    "CountryID": 4,
    "CountryName": "American Samoa"
  }, {
    "CountryID": 5,
    "CountryName": "Andorra"
  }, {
    "CountryID": 6,
    "CountryName": "Angola"
  }, {
    "CountryID": 7,
    "CountryName": "Anguilla"
  }, {
    "CountryID": 8,
    "CountryName": "Antarctica"
  }, {
    "CountryID": 9,
    "CountryName": "Antigua and Barbuda"
  }, {
    "CountryID": 10,
    "CountryName": "Argentina"
  }];

  $.each(country, function (index, item) {
    $('#ddlCountry').append($('<option></option>').val(item.CountryID).html(item.CountryName));
  });

  $('#ddlCountry').val(2);
});

我已将下拉值设置为 2,但默认值始终是 Select Country

这是 jsfiddle

最佳答案

当以编程方式更改 select 的选定值时,您不会触发 onchange 事件。手动触发:

$('#ddlCountry').val(2).change();

DEMO

关于javascript - 无法使用 jquery 设置选择的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18999640/

相关文章:

php - 将文本框(php)中的内容保存到 mySQL 中时没有任何反应

javascript - 在 javascript 中将数组映射到对象中的键

javascript - 无法向此动画中的 Z 添加框阴影或文本阴影

jquery propertychange 数组中存在 ID 的字段

javascript - 使用jquery根据url将文本和属性添加到div

javascript - 是否可以直接链接到 JavaScript onclick 函数?

带有 ASP.NET AJAX pageLoad() 函数的 Javascript 计时器

javascript - 将常规自定义 js 事件绑定(bind)到 Angular Controller 函数

jquery - 如何检查节点是元素还是文本

html - 使用 css 更改嵌套跨度样式具有样式标签