使用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);
      })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM