選擇不更新 (Select doesn't update)


問題描述

選擇不更新 (Select doesn't update)

當我更改選擇選項時,它不會更新值。框內內容的數量必鬚根據選擇選項而改變,但它不起作用。提前致謝。FIDDLE

$(function() {
  var all = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz\‑=_!#%&'*{},.\/:?\(\)\[\]@\\$\^*+<>~";
  var myLength = $("#mySelect option:selected").val();

  function randomAll() {
    for (var i = 0; i < myLength; i++) {
      var word = all[Math.floor(Math.random() * all.length)];
      $('#content').append(word + i++);
    }
  }

  $('#all').click(function() {
    $('#content').html('');
    randomAll();
  });

});
#content {
  width: 200px;
  height: 50px;
  border: 1px solid #333;
  margin‑top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="all">All</button>
<div id="content"></div>
<select id="mySelect">
  <option value="4" selected="selected">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>


參考解法

方法 1:

You need to bind to its change event

$('#mySelect').change(function(){
  $('#content').val($(this).val());
});

This will set it to the value of the option that is selected when it is changed.

方法 2:

get selected value inside the function

 function randomAll() {
        var myLength = $("#mySelect option:selected").val();
        for (var i = 0; i < myLength; i++) {
          var word = all[Math.floor(Math.random() * all.length)];
          $('#content').append(word + i++);
        }
      }

Demo

(by user4991434CWittyMohamed‑Yousef)

參考文件

  1. Select doesn't update (CC BY‑SA 2.5/3.0/4.0)

#jquery #input #select






相關問題

讓 jQuery 與 Netscape 7 和 8 一起工作 (Getting jQuery to work with Netscape 7 and 8)

使用 Jquery 的 mvc3 搜索結果 (mvc3 search results with Jquery)

從嵌套的 jquery 函數返回一個值 (Return a value from nested jquery function)

Mencocokkan lebar divisi dengan jquery (Matching division widths with jquery)

無法在 jQuery AJAX 中多次生成點擊事件 (unable to generate click event more than once in jQuery AJAX)

使用雙引號格式並用逗號分隔元素數組 (Implode an element array with double quote format and separated by comma)

選擇不更新 (Select doesn't update)

chrome中帶有省略號的多行文本問題 (issue with multiline text with ellipsis in chrome)

AJAX/PHP/JS - 無法將頁面內容加載到容器中 (AJAX/PHP/JS - Cannot load page content into container)

使用 jQuery 將文本插入 textarea (Insert text into textarea with jQuery)

滾動到頁面底部,僅當用戶在 DOM 操作之前已經位於底部時 (Scroll to bottom of page, only if the user already was at the bottom before DOM manipulation)

如何設置單選按鈕的樣式,使其看起來像普通的可點擊按鈕? (How do I style a radio button to look like a normal clickable button?)







留言討論