使用JQ 给 Select 设置不可选中的默认值后,获取值为null的问题

RT

<select id="test"></select>
var options = [
        {
          key: 1,
          name: 'a11111',
        },
        {
          key: 2,
          name: 'b222222',
        },
        {
          key: 3,
          name: 'c33333',
        },
        {
          key: 4,
          name: 'd4444444',
        },
      ]
      var optionHtml = ''
      options.forEach(function (item) {
        optionHtml += `<option value="${item.key}">${item.name}</option>`
      })
      $('#test').html(optionHtml)
      $(function () {
        setTimeout(() => {
          $('#test option').each(function () {
            var optionVal = $(this).val()
            if (Number(optionVal) === 2) {
              $(this).attr('disabled', 'disabled')
              $(this).attr('selected', 'selected')
            }
          })
        }, 1000)
        setTimeout(() => {
          console.log('错误的取值方法', $("#test").val())
          console.log('正确的取值方法', $("#test option:selected").val())
        }, 2000);
      })

posted @ 2020-09-28 14:26  Function-Fun  阅读(1064)  评论(0)    收藏  举报