在AJAX插入的动态创建元素上绑定事件(复选框)

Bind events on dynamic created elements inserted by AJAX (check box)

本文关键字:事件 绑定 复选框 元素 插入 AJAX 动态 创建      更新时间:2023-09-26

我是jQuery新手。我已经写了一个代码来添加产品从一个表到另一个动态检查像这样的FIDDLE:这段代码对我来说工作得很好,你可以看到在小提琴。

现在我已经通过使用ajax动态地生成这个产品列表(表2)来操作这段代码,现在这段代码对我不起作用了。

当我想到这个缺陷时,我认为我所有的CSS和JS脚本都是加载页面的,但是这个复选框(表2)是动态加载的,这就是为什么JS不接受这个 ....

那么如何在动态加载的输入字段上触发事件函数?我只是希望这个脚本得到改进:JQUERY 1.6.4.

我的观点是:

<div class="_25">
    <?php echo form_dropdown('class', $dropdown_class,'','id="clas"'); ?>
</div>
<div class="_25">           
    <?php echo form_dropdown('section',$dropdown_section); ?>
</div>  
    
<table class="table" border="1">
    <thead><tr>
        <th>Select</th>
        <th>Cause</th>
        <th>Monthly Charge</th>
    </tr></thead>
    <tbody id="selectedServices"></tbody>
    <tr>
        <td>Total-</td>
        <td>Fee</td>
        <td id="total">1500</td>
    </tr>
</table>
<!-- product list (will generate dynmiclly)like tble 2 in fiddle -->
<table id="abcd" class="table" border="1">
    <thead><tr>
        <th>Select</th>
        <th>Cause</th>
        <th>Monthly Charge</th>
    </tr></thead>
    <tbody id="name_sec">
        <!-- here your dat will appear as per selection of class ajax check the below function and related controller mthod 
        the value will come with chk box for selection ad prepering the data-->
    </tbody>
</table>
下面是我的脚本:
<script language="javascript">
jQuery(function ($) {
    $("#clas").change(function() {
        var send_data=$("#clas").val();
        $.ajax({
            type:"post",
            url:"show_additional_fee_chkbox_select",
            data:"send_data_post_for_chkbox="+send_data,
            success:function(data){
                $("#name_sec").html(data);
            }
       });
    });
                
    $(":checkbox").change(function () {
        // Toggle class of selected row
        $(this).parent().toggleClass("rowSelected");
        // Get all items name, sum total amount
        var sum = 1500;
        var arr = $("#abcd :checkbox:checked").map(function () {
            sum += Number($(this).parents('tr').find('td:last').text());
            return $(this).parents('tr').clone();
        }).get();
        // Display selected items and their sum
        $("#selectedServices").html(arr);
        $("#total").text(sum);
        
        $('#selectedServices :checkbox').change(function() {
            $('#selectedServices :checkbox:unchecked').parents('tr').remove();
        });
    });
});
</script>

我的控制器:

public function show_additional_fee_chkbox_select()
{
    $class=$_POST['send_data_post_for_chkbox'];
    //here goes ur process to display list of extra/additional fee 
    
    $extra_fee_list='';    
    $sql2="SELECT * FROM fee_additional_fee where class=?";
    $query2 = $this->db->query($sql2,$class);
    foreach ($query2->result_array() as $row2) {
        $extra_fee_list=$extra_fee_list.' 
        <tr>        
            <td>  
                <input type="checkbox" id="selectedServices" class="checkBoxClass" name="additional_fee_code[]"  value="'.$row2['id'].'"> Select</input>
            </td> 
            <td>'.$row2['cause_addition_fee'].'</td>
            <td>'.$row2['fee'].'</td>
        </tr>  ';
        // here again plz take input in  arry ----additional_fee_code will work for next method (cal_total_extra_fee())
    }
    echo $extra_fee_list;
}

我意识到,AJAX结果data是一个表行元素<tr>包含数据单元<td>、输入<input>等。

<标题>第一解决方案:

如果你想访问data内部的元素,这应该可以达到目的:

$(':checkbox', $(data));

因此,您可以在data准备好之后立即在内部元素上设置事件。

// Since jQuery 1.7
$(':checkbox', $(data)).on('click', function() {});
// Or
$(':checkbox', $(data)).click(function() {});

您也可以声明一个全局函数,并将其名称插入.click().on()方法中作为处理程序。

因此,只需编辑$.ajax部分,如下所示:
$.ajax({
    type    : "post",
    url     : "show_additional_fee_chkbox_select",
    data    : "send_data_post_for_chkbox="+send_data,
    success : function(data) {
        var html = $(data);
        $('input[type="checkbox"]', html).click(onClickFunction);
        $("#name_sec").html(html);
    }
});

这是一个JSBin Demo


<标题>第二方案

还有另一种方法可以将事件绑定到插入的元素上。

使用jQuery .find()方法可以是一个选项:

// Since jQuery 1.6
$('#name_sec').find(':checkbox').click(function() {
    // Do whatever you want
});

这应该放在$.ajax部分的$("#name_sec").html(data);之后。


<标题>第三种解决方案:

通过使用jQuery的.on()方法就像:

// Since jQuery 1.7
$('#name_sec').on('click', ':checkbox', function() {
    // Do whatever you want
});

您知道,当您在站点中创建新对象时,编写的javascript将无法识别它…除非…您使用jQuery的live方法,它将自我更新DOM的知识。

代替:

$(my_check_box_class).click(function() {...})

使用:

$(my_check_box_class).live("click", function()
{
 var id_selecionado = $(this).attr('id');  
 $.ajax(
 {...

明白了吗?