2

何らかの理由で、正しく機能するために 2 回連続してクリックする必要がある JavaScript があります。リンクのコードは次のとおりです。

<a href="" onclick="select_all_com(); return false">Select All</a>

次に、onclick で呼び出される関数のコードを示します。

function select_all_com(){
$("[name=file_com_appeal].com-checkbox").each( function() {   
    $(this).attr('checked', true);
}); 
UpdateTotalFee();
}

最後に、最後のコードは次のとおりです。

function UpdateTotalFee(){
    var AppealCount = 0;

    $('input[name=file_com_appeal].com-checkbox').each(function(){
    if( $(this).next().hasClass('checked') ){ 
        AppealCount++; } 
    });

    $('#AppealFeeTotal').text("$"+(AppealCount*140));
}

この最後の部分は、リンクが最初にクリックされたときに実行されるはずですが、何らかの理由で最初は実行されず、2 回目だけ実行されます。具体的には、最初のクリックですべてのチェックボックスがオフからオンに更新されますが、#AppealFeeTotal. チェックボックスがすでに選択されている場合に、[すべて選択] リンクをクリックすると、#AppealFeeTotalが更新されます。

これが2回のクリックを必要とする理由はありますか? また、特によくわからないコード行が 1 行あることも付け加えておきます。私は他の誰かからコードを継承しましたが、これが使用される理由がわかりません:

if( $(this).next().hasClass('checked') ){

アイデアをお寄せいただきありがとうございます。

4

2 に答える 2

2

いくつかのことは、最初に、これがあなたの問題があると思われるものattr('checked')と同じではありません。hasClass('checked')あなたのコードは、私が見ることができる「チェック済み」クラスを追加しませんが、それが当てはまる場所を数えています。is:checkedこれにはセレクターを使用する必要があります。

第二に、あなたのコードを正しく読んだ場合、あなたはチェックされたチェックボックスを数えて合計を取得しているだけです. これをより効率的に行うには、次のようにします。

$(":checkbox").filter(':checked').length

当然、そのセレクターを改良したいと思うでしょう (そのため、特定のチェックボックスのみをカウントします)。

于 2012-12-26T04:25:25.950 に答える
1
$(document).ready( function() { // this is a function which execute when document is ready in jQuery
var clicks = 0; // I am taking clicks variable so, to check whether the user have clicked for the first time

$("a").on("click", function() { // this is a function which execute when target anchor tag is clicked
    clicks++; // now user have clicked the anchor tag so, i have to increase value to 1
    if(clicks==1) { // this condition checks whether user have clicked the anchor tag for the first time? if yes, then execute the code
        $("[name=file_com_appeal].com-checkbox").each( function() { // this is a each function which loops through all targets perform operations
        $(this).attr('checked', true); // while looping through all targets this will set attribute or property "checked" to true means its checked
        });
    }
    else if(clicks==2) { // this conditions check that whether anchor tag is clicked for second time
        var AppealCount = 0;
        $('input[name=file_com_appeal].com-checkbox').each(function(){
            if( $(this).prop('checked') ){ 
                AppealCount++; 
            } 
        });
        $('#AppealFeeTotal').text("$"+(AppealCount*140));
        clicks = 0; // set to zero because if user repeatedly clicks the anchor tag
    }
});
});
于 2012-12-26T04:23:19.133 に答える