[英]jQuery .change() not responding as expected
我有一个select
要尝试执行jQuery .change
事件。 由于某种原因,它无法识别选择的id
。 它是通过另一个AJAX
调用来构建的,该调用创建了一个select及其选项的php文件。
<script>
$(document).ready(function()
{
$("#unitselector").on('change', function()
{
console.log('made it');
var unit=$('#unitselector').filter(':selected').val();
var dataString = {unit:unit};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/unit_info.php",
data: dataString,
cache: false,
success: function(html)
{
$('.unitinfo').html(html);
}
});
});
});
</script>
相关的PHP:
echo '<select id="unitselector" name="units">';
while( $row = mysqli_fetch_assoc($result))
{
$units[] = $row['unit_name'];
echo '<option value="'.$row['unit_name'].'">'.$row['unit_name'].'</option>';
}
echo '</select>';
It is built through another AJAX call to a php file that creates the select and its options.
这意味着它是动态添加到DOM的,因此需要事件委托。 jQuery 1.7+使用.on()方法以便正确绑定。
$("#unitselector").on('change', function()
至
$(document).on('change', '#unitselector', function()
此外,确实没有理由像您所做的那样尝试获得价值。 您位于元素内部,因此可以通过this
它是本机javascript对象)或$(this)
它是jQuery对象)进行访问,无论哪种方式都可以正常工作。
var unit = $(this).val();
//or
var unit = this.value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.