这里的第一个问题,所以我会尽力遵守所有规则。

我有一个包含2个选择组的PHP页面,默认情况下禁用第二个组。

第一个选择组称为“年列表”,第二个选择组称为“ makelist”

当用户更改年列表中的选择时,第二个框(makelist)将使用数据库表中的选择填充(通过我的script.js中的ajax请求),并且不再被禁用。

当我在第二个选择组(makelist)中进行选择时,就会出现问题。我希望jQuery在注意到该makelist组中的用户所做的更改时发出一个简单的alert(“ 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元素和附加的change事件,因此您拥有一个新的#makelist元素,但没有change事件。将$('#makelist')。change()函数放在$ .get回调函数中。

$.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与旧ID相同。

07-24 17:12