2012-07-26 104 views
0

我在执行ajax调用后构造了2个复选框。当我尝试引用它们的id来执行.change()事件时,事件不会触发。有任何想法吗?这里是我的代码:Jquery .change()事件问题

Ajax调用:

$.ajax({       
    url:"../includes/MC.Admin.ajax.php", 
    type: "POST", 
    data: empupdatedata, 
    success: function(empupdate) {    
    var empupdateJson = $.parseJSON(empupdate); 

        $("#empupdateinfo_tbl").html(empupdateJson.updateempinfo); 

       $("#empemploymentupdateinfo_tbl").html(empupdateJson.updateempemploymentinfo); 


       $('#employee-update').bPopup({ 
        modalClose: false 
       }); 

       } 
     }); 

这是构建文本框:

if($rm5->isbonus == 1 && $rm5->isallowance == 0) 
{ 
    $updateemployeeemploymentinfo .= "<tr><td class = 'tbl_data'> 
    Additional Payment</td><td>Bonus <input type = 'checkbox' 
    name = 'isbonus' id = 'uisbonus'> Allowance <input type = 'checkbox' 
    name = 'isallowanece' id = 'uisallowance'></td></tr><tr></tr>"; 
} 

我想用这两个复选框的ID的触发更改事件使用以下代码:

$("#uisbonus").change(function(){ 
    if($(this).attr("checked")) 
    { 
     $('#uamountcon').append("<td id = 'uamountcon'><input type = 'text' id = 'uamount ></td>") 

    } 
    else 
    { 
     $('#uamountcon').html(); 
    } 
}); 

$("#uisallowance").change(function(){ 
    if($(this).attr("checked")) 
    { 
     $('#uamountcon').append("<td id = 'uamountcon'><input type = 'text' id = 'uamount ></td>") 
    } 
    else 
    { 
     $('#uamountcon').html(); 
    } 
});//I placed this code insidethe $(document).ready(function() { }); 

更改事件的位置是否错误?我应该在哪里举办活动?或者是什么问题?谢谢!

+0

你在控制台中的错误?你预计什么时候开火? – bPratik 2012-07-26 15:57:25

+1

将元素添加到页面(在ajax成功范围内)后直接将更改事件绑定移动,或者使用'.delegate'或'.on'与委托语法绑定事件。 – 2012-07-26 15:57:34

+1

您的问题缺少有关_when_您尝试绑定处理程序的信息。它可能是你实际插入元素之前绑定的。您可能想看看jquerys live()方法或其后继者。 – arkascha 2012-07-26 15:57:53

回答

1

因为您将它们添加在页面加载后,你将不得不使用on()delegate()事件代表团。 on()已于1.7版本中增加,但对于以前版本delegate()是使用事件委托的最有效方法。

$("body").delegate("#uisbonus", "change", function(){ 
... 
$("body").delegate("#uisallowance", "change", function(){ 

这可能是更好的参考的class而不是id

$("body").delegate(".uiClassName", "change", function(){ 
+0

我应该把代码放在document.ready?或者在ajax调用之后?放置在document.ready中时似乎不起作用。 – ljpv14 2012-07-26 16:07:33

+0

从技术上说,没关系,但是你可以把它放在'$(document).ready(function(){...})'声明中。 – RobB 2012-07-26 16:08:45

+0

得到它的工作。谢谢!关于我的帖子的另一个问题你为什么认为表格数据追加没有被触发的原因?谢谢 – ljpv14 2012-07-26 16:13:58

0

事件代表团将是最简单的解决,

$(document).delegate("#uisbonus","change",function(){ 
    if($(this).attr("checked")) 
    { 
     $('#uamountcon').append("<td id = 'uamountcon'><input type = 'text' id = 'uamount ></td>") 

    } 
    else 
    { 
     $('#uamountcon').html(); 
    } 
}); 

$(document).delegate("#uisallowance","change",function(){ 
    if($(this).attr("checked")) 
    { 
     $('#uamountcon').append("<td id = 'uamountcon'><input type = 'text' id = 'uamount ></td>") 
    } 
    else 
    { 
     $('#uamountcon').html(); 
    } 
});