.change()

.change( handler(eventObject) ) 官网原E文: jQuery

描述: 为 "change" 事件绑定一个处理函数,或者触发元素上的 "change" 事件。

  • version added: 1.0.change( handler(eventObject) )

    handler(eventObject)每次事件触发时会执行的函数。

  • version added: 1.4.3.change( [ eventData ], handler(eventObject) )

    eventData将要传递给事件处理函数的数据映射。

    handler(eventObject)每次事件触发时会执行的函数。

  • version added: 1.0.change()

这个函数的第一种用法是 .bind('change', handler) 的快捷方式,第二种用法是 .bind('change') 的快捷方式。

一个元素的值改变的时候将触发change事件。此事件仅限于<input>元素,<textarea>框和<select>元素。对于选择框,复选框和单选按钮,当用户用鼠标作出选择,该事件立即触发,但对于其他类型元素,该事件触发将推迟到元素失去焦点。

举例来说,请看下面的HTML:

<form>
  <input class="target" type="text" value="Field 1" />
  <select class="target">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
</form>
<div id="other">
  Trigger the handler
</div>

事件处理函数可以绑定到文本输入和选择框:

$('.target').change(function() {
  alert('Handler for .change() called.');
});

现在,当下拉菜单中第二个选项被选择,警报显示。如果我们改变了在这一领域的文本,然后点击警报也会显示。如果该域的内容没有变化失去焦点,该事件不会被触发。点击另一个元素时,我们可以手动触发这个事件:

$('#other').click(function() {
  $('.target').change();
});

这些代码执行后,点击Trigger the handler也提醒消息。该信息将显示两次,因为表单元素都绑定了change事件处的理函数。

在jQuery 1.4中 change事件是冒泡的,在Internet Explorer和其他浏览器中运行是一样的。.

例子:

Example: Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.

<!DOCTYPE html>
<html>
<head>
  <style>

  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <select name="sweets" multiple="multiple">
    <option>Chocolate</option>
    <option selected="selected">Candy</option>

    <option>Taffy</option>
    <option selected="selected">Caramel</option>
    <option>Fudge</option>
    <option>Cookie</option>

  </select>
  <div></div>
<script>
    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .change();
</script>

</body>
</html>

Demo:

Example: To add a validity test to all text input elements:

$("input[type='text']").change( function() {
  // check input ($(this).val()) for validity here
});
jQuery 1.6 API 中文版Clove整理、修订