jquery 第二个Selectpicker on change事件不起作用[重复]

piok6c0g  于 2023-06-22  发布在  jQuery
关注(0)|答案(2)|浏览(278)

此问题已在此处有答案

Event binding on dynamically created elements?(23答案)
12天前关闭
我有两个选择器。一个是城市,另一个是城镇。当citySelectpicker更改时,我用 AJAX 加载城镇。
这是没有问题的。当我试图在TownSelect上更改事件时,发生了nathing。TownSelect onchange不工作。
但我刷新页面。并直接更改townSelect Change事件的工作原理。但在此之前,我使用CityChange它是不工作的。
index.php

<!DOCTYPE html>
<html lang="en" class="no-js">

<head>

    <meta charset="UTF-8">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-select.css" />
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
    <script src="js/bootstrap-select.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="css/jquery-ui.css">

    <?php
    header("Cache-Control: no cache");
    ?>

</head>

<body>

<div class="cityList col-lg-3 col-md-6 col-sm-3">
    <label for="citySelect2" class="labelsfilter ml-2">City</label>
    <select class="selectpicker mb-3" id="citySelect2" name="citySelect2" data-width="100%" data-live-search="false" required="required">
        <option value="">Select City</option>
    <?php
    $myQuery = "SELECT * FROM tessCityTable";
    $statement = $konn->prepare($myQuery);
    $statement->execute();
    $results = $statement->fetchAll(PDO::FETCH_ASSOC);
    if ($results){
        foreach ($results as $result){
            if (isset($cityID2)){
                if ($cityID2 == $result['cityID']){
                    echo ('<option value="'.$result['cityID'].'" selected>'.$result['cityName'].'</option>');
                }
                else {
                    echo ('<option value="'.$result['cityID'].'">'.$result['cityName'].'</option>');
                }
            }
            else {
                echo ('<option value="'.$result['cityID'].'">'.$result['cityName'].'</option>');
            }
            
        }
    }

    ?>
    </select>
</div>                  

<div id="townList2" class="townList2 col-lg-3 col-md-6 col-sm-3">
    <label for="townSelect2" class="labelsfilter ml-2">Town</label>
    <select class="selectpicker mb-3 show-tick townSelect2" id="townSelect2" name="townSelect2[]" multiple="multiple" data-live-search="false" data-width="100%" data-selected-text-format="count">
        <option value="0">Select Town</option>
    </select>
</div>

</body>

</html>

<script>            
$(document).ready(function() {
    $('#townSelect2').selectpicker();

    $("#citySelect2").change(function() {
        var selectedCity = $(this).val();

        $.ajax({
            type: "POST",
            url: "query.php",
            data: 'keyword=' + selectedCity,
            success: function(data) {
                var response = JSON.parse(data);

                $('.townList2').html(response.townList);
                $('.townSelect2').selectpicker('refresh');

            }
        });
    });

    $('#townSelect2').on('changed.bs.select', function(e) {
        //Nothing Happens
            console.log("changed.bs.select event triggered");
            console.log("e:", e);
        
    });

    $("#townSelect2").change(function() {
        //Nothing Happens
        console.log("changeEvent");
    });

})

</script>

和query.php

if (!empty($_POST["keyword"])) {
    $townList = "";
    $cityID = $_POST['keyword'];
    $myQuery = "SELECT * FROM tessTownTable WHERE cityID=:cityID";
    $statement = $konn->prepare($myQuery);    
    $statement->bindParam(':cityID', $cityID);
    $statement->execute();
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);
    if (!empty($result)) {
        
        $townList = $townList . '<label for="townSelect2" class="labelsfilter ml-2">İlçe</label>';
        $townList = $townList . '<select class="selectpicker mb-3 show-tick townSelect2" id="townSelect2" name="townSelect2[]" multiple="multiple" data-live-search="false" data-width="100%" data-selected-text-format="count">';
        $townList = $townList . '<option value="0">İlçe Seçiniz</option>';
  
        foreach ($result as $town) { 
            $townList = $townList . '<option value="'.$town['townID'].'">'.$town['townName'].'</option>';
        }
        $townList = $townList . '</select>';

        $konn = null;
        $statement = null;

        $response = array(
            "townList" => $townList
        );
        
        $jsonResponse = json_encode($response);

        echo $jsonResponse;  
    }
}
wrrgggsh

wrrgggsh1#

这里有一个答案。但是我真的不想使用obServer。但是找不到任何解决方案,如果我找到任何没有obServer的东西,我会更新答案。
请检查JavaScript部分。

<!DOCTYPE html>
<html lang="en" class="no-js">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-select.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
    <script src="js/bootstrap-select.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="css/jquery-ui.css">
    <?php
    header("Cache-Control: no cache");
    ?>
</head>

<body>

    <div class="cityList col-lg-3 col-md-6 col-sm-3">
        <label for="citySelect2" class="labelsfilter ml-2">City</label>
        <select class="selectpicker mb-3" id="citySelect2" name="citySelect2" data-width="100%" data-live-search="false" required="required">
            <option value="">Select City</option>
            <?php
            $myQuery = "SELECT * FROM tessCityTable";
            $statement = $konn->prepare($myQuery);
            $statement->execute();
            $results = $statement->fetchAll(PDO::FETCH_ASSOC);
            if ($results) {
                foreach ($results as $result) {
                    if (isset($cityID2)) {
                        if ($cityID2 == $result['cityID']) {
                            echo ('<option value="' . $result['cityID'] . '" selected>' . $result['cityName'] . '</option>');
                        } else {
                            echo ('<option value="' . $result['cityID'] . '">' . $result['cityName'] . '</option>');
                        }
                    } else {
                        echo ('<option value="' . $result['cityID'] . '">' . $result['cityName'] . '</option>');
                    }
                }
            }
            ?>
        </select>
    </div>

    <div id="townList2" class="townList2 col-lg-3 col-md-6 col-sm-3">
        <label for="townSelect2" class="labelsfilter ml-2">Town</label>
        <select class="selectpicker mb-3 show-tick townSelect2" id="townSelect2" name="townSelect2[]" multiple="multiple" data-live-search="false" data-width="100%" data-selected-text-format="count">
            <option value="0">Select Town</option>
        </select>
    </div>

    <script>
        $(document).ready(function() {
            $('#townSelect2').selectpicker();

            $("#citySelect2").change(function() {
                var selectedCity = $(this).val();

                $.ajax({
                    type: "POST",
                    url: "query.php",
                    data: 'keyword=' + selectedCity,
                    success: function(data) {
                        var response = JSON.parse(data);

                        $('.townList2').html(response.townList);
                        $('#townSelect2').selectpicker('refresh');

                        $('#townSelect2').on('changed.bs.select', function(e) {
                            console.log("changed.bs.select event triggered");
                            console.log("e:", e);
                        }).trigger('change'); 

                    }
                });
            });

            $("#townSelect2").change(function() {
                console.log("changeEvent");
            });

            
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === "childList" && mutation.target.id === "townSelect2") {
                        console.log("townSelect2 DOM değişikliği");
                        console.log(mutation);
                    }
                });
            });

            
            observer.observe(document.getElementById("townSelect2"), {
                childList: true, 
                subtree: true 
            });

        });
    </script>

</body>

</html>
hi3rlvi2

hi3rlvi22#

[TL:DR]:

交换

$('#townSelect2').on('changed.bs.select', function() {...})

$('body').on('changed.bs.select', '#townSelect2', function() {...})

和使用

$('.townList2').replaceWith(response.townList);

而不是

$('.townList2').html(response.townList);

您需要使用event delegation才能在动态添加的元素(如townSelect2- select)上使用事件。

说明:

如果将changed.bs.select-事件的事件处理程序附加到所有id为townSelect2的元素,则该事件将附加到加载脚本时DOM中存在的所有id为townSelect2的元素。这意味着,当你动态添加一个元素到DOM时,你必须再次附加事件,就像你 AJAX 成功中所做的那样,或者你需要将事件委托给一个父元素,当你的DOM加载时,它实际上是存在的。

/* Attach the event to the body (or any other parent element of your select)
  the event will then bubble up until it "finds" the element with the 
  townSelect2 id and trigger */
$('body').on('changed.bs.select', '#townSelect2', function() {...})

此外,您将从PHP端点返回一个完整的<select>元素,但您正在使用.html(...)将其插入当前的<select>元素中。您需要替换它,以防止无效的HTML,如下所示:

<select class="..." id="..."><select class="..." id="...">...</select></select>

相关问题