简体   繁体   English

Jquery中动态添加元素的绑定事件不起作用

[英]Bind event for dynamic added elements in Jquery not working

I have added Address , city and locality using jQuery in a dynamic added div element where the binding event is not working as expected: I have below jQuery code:我在动态添加的 div 元素中使用 jQuery 添加了Addresscitylocality ,其中绑定事件未按预期工作:我有以下 jQuery 代码:

<script type="text/javascript">
    $(document).ready(function () {
        var counter = 0;
        $(document).on('click', '#addButton', function (e) {
            if (counter > 19) {
                alert("Only 20 Address allowed");
                return false;
            }
            e.preventDefault();

            var elems = '<div class="col-lg-5"  id="Address' + counter + '">' +
                    '<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
                    '<div class="col-lg-3 form-group" id="city' + counter + '">' +
                    '<select name="city_name[]" id="city_name' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
                    '</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
                    '<div class="col-lg-1 form-group">' +
                    '<button type="button" class="removebtn" id="removeButton' + counter + '">' +
                    '<span class="glyphicon glyphicon-minus"></span></button>' +
                    '</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';

            //('#addressDiv').append(elems);
            $('#addressDiv').append(elems);


            $.ajax({
                type: "Post",
                url: "city_load.php",
                success: function (html) {
                    $('#city_name' + counter).html(html);
                }

            });


            $(document).on('change', '#city_name' + counter, function (ev) {

                ev.preventDefault();
                $city_id = $(this).val();

                $.ajax({
                    type: "Post",
                    url: "ajax-dd3ck.php",
                    data: "city_id=" + $city_id,
                    cache: "false",
                    success: function (html) {

                        $('#locality_name' + counter).html(html);

                    }

                });


            });
            //counter++;
            return false;
        });
        $(document).on('click', '.removebtn', function () {

            if (counter == 0)
            {
                alert("No more textbox to remove");
                return false;
            }

            counter--;

            $("#Address" + counter).remove();
            $("#removeButton" + counter).remove();

        });

    });
</script>

My PHP Code for adding city in dropdown我的用于在下拉列表中添加城市的 PHP 代码

city_load.php: city_load.php:

<?php

include("db.php");
$sql = "select * from city";
echo "<select name='city_name[]' id='city' class='city1'><option value='' selected ='selected'>Select City</option>";
$res = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($res)) {

    echo "<option value='$row[city_id]'>$row[city_name]</option>";
}
echo "</select>";
?>
                     

locality_load.php locality_load.php

<?php

include("db.php");
$city_id = $_POST['city_id'];

$sql = "select locality_id,locality_name,city_id from locality where city_id=$city_id";

$res = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql) or die("query error");
while ($rows = mysqli_fetch_array($result)) {



    $locality_id = $rows['locality_id'];

    $locality_name = $rows['locality_name'];

    echo "<option value=" . $locality_id . ">" . $locality_name . "</option>";

    //echo '<option value="'.$locality_id.'">'.$locality_name.'</option>';
}
?>
                     

The issue I am getting is that the first dynamic div is getting added and data is loading properly but for 2nd dynamic div it is not working.我遇到的问题是第一个动态 div 正在添加并且数据正在正确加载,但是对于第二个动态 div 它不起作用。 Please have a look on screenshot:请看截图:

https://snag.gy/CBXvz.jpg

$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
    if (counter > 19) {
        alert("Only 20 Address allowed");
        return false;
    }
    e.preventDefault();

    var $elems = $('<div class="col-lg-5"  id="Address' + counter + '">' +
            '<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
            '<div class="col-lg-3 form-group" id="city' + counter + '">' +
            '<select name="city_name[]" id="city_name' + counter + '" data-index="' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
            '</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
            '<div class="col-lg-1 form-group">' +
            '<button type="button" class="removebtn" id="removeButton' + counter + '">' +
            '<span class="glyphicon glyphicon-minus"></span></button>' +
            '</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>');

    //('#addressDiv').append(elems);
    $('#addressDiv').append($elems);

    $.ajax({
        type: "Post",
        url: "city_load.php",
        success: function (html) {
            $elelms.find('select').html(html);
        }

    });

    counter++;
    return false;
});
$(document).on('change', 'select', function (ev) {
    var cc = $(this).attr('data-index');
    ev.preventDefault();
    $city_id = $(this).val();

    $.ajax({
        type: "Post",
        url: "ajax-dd3ck.php",
        data: "city_id=" + $city_id,
        cache: "false",
        success: function (html) {
            $('#locality_name' + cc).html(html);
        }
    });
});
$(document).on('click', '.removebtn', function () {

    if (counter == 0)
    {
        alert("No more textbox to remove");
        return false;
    }

    counter--;

    $("#Address" + counter).remove();
    $("#removeButton" + counter).remove();

});

}); });

There are maybe some problem!可能有点问题!

save the counter value as a data-attr eg将计数器值保存为数据属性,例如

var elems = '<div class="col-lg-5 Address"  data-id="' + counter + '">' +
                '<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
                '<div class="col-lg-3 form-group city" data-id="' + counter + '">' +
                '<select name="city_name[]" data-id="' + counter + '" class="form-control city_name"><option value="" selected ="selected">Select City</option></select>' +
                '</div><div class="col-lg-3 form-group"><select name="locality_name[]" data-id="' + counter + '" class="form-control locality_name"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
                '<div class="col-lg-1 form-group">' +
                '<button type="button" class="removebtn" data-id="' + counter + '">' +
                '<span class="glyphicon glyphicon-minus"></span></button>' +
                '</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';

use a class for each element , bind events on class .为每个元素使用一个类,在类上绑定事件。 like喜欢

$(document).on('change','.city_name', function (ev) {
  counter_id = $(this).attr('data-id');
 }

so you will get the counter value and hope it will work for every div you created.所以您将获得计数器值,并希望它适用于您创建的每个 div。 (code not tested ) (代码未测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM