如何查找多个.change()事件,这些事件指向正在被AJAX操作的项

How do I look for multiple .change() events to items that are being manipulated with AJAX

本文关键字:事件 操作 AJAX 查找 何查找 change      更新时间:2023-09-26

第一个问题,我会尽量遵守所有的规则。

我有一个PHP页面,有两个选择组,第二组是默认禁用的。

第一个选择组称为"yearlist",第二个选择组称为"makelist"

当用户更改yearlist中的选项时,第二个框(makelist)将用数据库表中的选项填充(通过my 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>

使用

    $('div.makeResult').html(data);

您正在删除#makelist元素和附加的更改事件,因此您有一个新的#makelist元素,但没有更改事件。将$('#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,该事件也将消失。

正如James L所说,当您覆盖#makelist DOM节点时,它会被破坏,因此不再附加事件处理程序。

不是

$('#makelist').change(function () {})

你可以用

$(document).on('change', '#makelist', function() {})

这将事件处理程序附加到文档,它将始终被调用。