这里的第一个问题,所以我会尽力遵守所有规则。
我有一个有2个选择组的PHP页面,默认情况下禁用第2组。
第一个选择组称为“年级列表”,第二个选择组称为“makelist”
当用户更改年度列表中的选项时,第二个框(makelist)将填入数据库表中的选项(通过我的script.js中的ajax请求),并且不再禁用。
当我在第二个选择组makelist中进行选择时,我的问题就出现了。我希望jQuery在注意到用户在该makelist组中所做的更改时发出一个简单的警报(“hello”),但它不起作用,我不确定原因。
主要文件:
<?php
$con = mysqli_connect("localhost","xxxx","xxxx","xxxx");
$query="SELECT * FROM carstats GROUP BY year ORDER BY year DESC";
$result = mysqli_query($con, $query);
?>
<script type="text/javascript" src="js/script.js"></script>
<select id="yearlist" name="yearlist">
<option>SELECT YEAR</option>
<?php
while ($row=mysqli_fetch_array($result)){
echo "<option>" . $row['year']. "</option>";
}
?>
</select>
<!--this will be populated/replaced via ajax-->
<div class="makeResult">
<select id="makelist" name="makelist" disabled="disabled">
<option>SELECT MAKE</option>
</select>
</div>
jQuery(script.js):
$(document).ready(function() {
$('#yearlist').change(function() {
//save the selection as a variable
var selectedYear = $(this).val();
$.get("change_query.php?selectedYear="+selectedYear, function(data){
$('div.makeResult').html(data);
});//end get function
});//end yearlist change function
$('#makelist').change(function() {
//eventually want to do more but for now just alert that it's working
alert("makelist has been changed");
});//end makelist change function
});//end ready function
,最后是change_query.php文件:
<?php
$con = mysqli_connect("localhost","xxxx","xxxx","xxxx");
$year = $_GET["selectedYear"];//this is grabbed from the JS script
$query="SELECT * FROM carstats WHERE year='".$year."' GROUP BY make ORDER BY make";
$result = mysqli_query($con, $query);
?>
<select id="makelist" name="makelist">
<option>SELECT MAKE</option>
<?php
while ($row=mysqli_fetch_array($result)){
echo "<option>" . $row['make']. "</option>";
}
?>
</select>
答案 0 :(得分:1)
使用时:
$('div.makeResult').html(data);
您正在删除附加的#makelist元素和更改事件,因此您有一个新的#makelist元素,但没有更改事件。在$ .get回调函数中放置$('#makelist')。change()函数。
$.get("change_query.php?selectedYear="+selectedYear, function(data){
$('div.makeResult').html(data);
$('#makelist').change(function() {
//eventually want to do more but for now just alert that it's working
alert("makelist has been changed");
});//end makelist change function
});//end get function
只是为了澄清,当您附加像$('#makelist')。change(...)这样的事件时,您将该事件附加到元素而不是ID。如果替换元素,则事件将消失,即使该元素具有与旧元素相同的ID。
答案 1 :(得分:1)
正如James L所说,发生的事情是#makelist
DOM节点在覆盖时会被破坏,因此不再附加事件处理程序。
而不是
$('#makelist').change(function () {})
您可以使用
$(document).on('change', '#makelist', function() {})
这会将事件处理程序附加到文档中,它将始终被调用。