0

这个问题真的很奇怪。我想要做的是将复选框值添加到隐藏字段,如果未选中则从隐藏字段中删除该值。我使用javascript来实现这一点,但是,我发现只有我调用一次警报,代码才有效,否则不会。谁能告诉我为什么?

var cpo={
    AddCheckList:function(){
    alert('aaaaaaaaaa'); //If I comment this line, the following code won't work.
    $(".BillChecked").change(function() {
            if ($(this).is(':checked')) {
                var idList = $('#CPO_BillList').val() + $(this).attr('value') + ",";
                $('#CPO_BillList').val(idList);
            } else {
                var temp = $('#CPO_BillList').val().replace($(this).attr('value') + ',', '');
                $('#CPO_BillList').val(temp);
            }
            alert($('#CPO_BillList').val());
    });
}

我打电话给 cpo.AddCheckList(); 在页面的底部。

上面是 $(document).ready() 函数。仅在调用一次警报方法时才有效。

4

2 回答 2

0

The alert dialog blocks the execution of the rest of your javascript. One of the following will work:

put the code in

$(document).ready(function{
    /*code here*/
});

or place the script-block at the bottom of your <body> tag.

Also you should store $(".BillChecked") in a variable because every jQuery-call with a Selector inside is pretty costly.

var $billChecked = $(".BillChecked");
于 2012-08-17T19:23:49.520 回答
0

试试这种方式,检查代码并避免循环。

$(document).ready(function(){

    var billChecked = $(".BillChecked");
    var cpoBill = $('#CPO_BillList');

    var cpo = {AddCheckList:function(){

        billChecked.change(function(){

            var checked = $(this).is(':checked');
            var billVal = $(this).val();

            checked ? v = cpoBill.val() + billVal : v = cpoBill.val().replace(billVal + ',', '');
            cpoBill.val(v);
        });
    };

});
于 2012-08-17T19:22:02.667 回答