选择1更新选择2,但选择2不会触发

时间:2012-02-21 23:57:56

标签: javascript jquery select onchange

我正在尝试选择1更新选择2,然后选择2开火。

选择2只在直接控制时开火..我很难过!!

代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select Firing</title> 
</head>
<body>
<p>Select 1 updates Select 2, but select 2's alert does not fire</p>
<select id="select1">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>
<p>Select 2 only fires alert when controlled directly</p>
<div>
<select id="select2" onchange="alert(this.value)">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>
</div>
</body>
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$(function() { //run on document.ready
  $("#select1").change(function() { //this occurs when select 1 changes
    $("#select2").val($(this).val());
  });
});
});
</script>
</html>

谢谢!

1 个答案:

答案 0 :(得分:6)

$("#select1").change(function() {

    $("#select2").val($(this).val()).trigger('change');
    //or
    $("#select2").val($(this).val()).change();

});

这是你需要的吗?或者我错过了什么?