javascript - 选择更新后未显示正确的选定值

标签 javascript jquery

这是我在 html 中的选择:

<select id="bgPosition">
    <option value="left top" selected="selected">Left Top</option>
    <option value="center top">Center Top</option>
    ..
</select>

在页面加载时,我需要用另一个值更新所选值,因此我尝试使用 .each .prop 和这个:

function setActiveOption(el,val){   
    $(el).find('option:selected').removeAttr('selected');
    $(el).find('option[value="'+val+'"]').attr('selected','selected');
    console.log('selected: '+$('#bgPosition').val())
}

对于其他选择框都可以,但对于 #bgPosition 则不行,我认为是因为值包含空格。

selected 属性位于正确位置,但将第一个选项显示为选定

知道如何解决这个问题吗?

我还尝试了不同的 jQuery 库

更新:这是my fiddle以及我如何运行函数。

最佳答案

鉴于您的示例 fiddle ,唯一不尊重您设置的值的 select 元素是中间的元素,#bgRepeat,这是因为默认情况下您'我们有两个使用 selected 属性设置的option

要解决此问题,只需提供一个带有 selected 属性的 option

话虽这么说,更好的解决方案是仅使用 .val() 作为 select 本身的 setter,这是一个单行代码,因此会呈现setActiveOption() 函数是多余的。试试这个:

var template = [{
  "mainBgImgPosition": "right bottom",
  "mainBgImgRepeat": "no-repeat",
  "mainBgImgSize": "cover"
}]

jQuery(function($) {
  var Builder = {
    initialized: false,
    initialize: function() {
      if (this.initialized)
        return;

      this.initialized = true;
      $('#bgPosition').val(template[0].mainBgImgPosition);
      $('#bgRepeat').val(template[0].mainBgImgRepeat);
      $('#bgSize').val(template[0].mainBgImgSize);
    }
  }
  Builder.initialize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="bgPosition" id="bgPosition">
  <option value="left top" selected="selected">Left Top</option>
  <option value="left center">Left Center</option>
  <option value="left bottom">Left Bottom</option>
  <option value="center top">Center Top</option>
  <option value="center center">Center Center</option>
  <option value="center bottom">Center Bottom</option>
  <option value="right top">Right Top</option>
  <option value="right center">Right Center</option>
  <option value="right bottom">Right Bottom</option>
</select>
<select name="bgRepeat" id="bgRepeat">
  <option value="repeat" selected="selected">Repeat All</option>
  <option value="repeat-x">Repeat X</option>
  <option value="repeat-y">Repeat Y</option>
  <option value="no-repeat">No Repeat</option>
</select>
<select name="bgSize" id="bgSize">
  <option value="auto" selected="selected">Auto</option>
  <option value="cover">Cover</option>
</select>

关于javascript - 选择更新后未显示正确的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43072635/

相关文章:

javascript - geocoder.geocode 仅在特定条件下有效

javascript - 如何在谷歌地图中心显示点动画?

php - debugURIComponent(uri) 不起作用?

javascript - 使用 jQuery 转义 HTML

javascript - jQuery 菜单不加载 PHP 子类别

javascript - 如何阻止地址自动填充谷歌地点

javascript - Jquery 下拉菜单更改悬停时的字体粗细

javascript - 此页面上的不同元素似乎以不同的速度滚动。这是怎么做到的?

jquery - 有没有等同于 jQuery.offset 的 Elm?

javascript - 使用jQuery将元素移动到倒数第二个h2之前