2017-02-26 169 views
2
var countChecked = function() { 
    var n = $("input:checked").length; 
    $("#count").text(n + (n === 1 ? " is" : " are") + " checked!"); 
}; 

countChecked(); 
alert();  // this alert 

$("input[type=checkbox]").on("click", countChecked); 

我使用此代碼來計算檢查的複選框輸入的數量。Jquery代碼無法正常工作

alert()這個效果很好。但沒有警報,這是行不通的。我該如何解決它?

回答

3

只有一行代碼就足夠了您的結果: -

$("input[type=checkbox]").on("click",function(){ 
 
    alert($("input[type=checkbox]:checked").length); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input type="checkbox" name="vehicle" value="Cycle"> I have a cycle<br> 
 
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br> 
 
<input type="checkbox" name="vehicle" value="Auto"> I have a Auto<br> 
 
<input type="checkbox" name="vehicle" value="Car"> I have a car<br> 
 
<input type="checkbox" name="vehicle" value="Bus"> I have a bus<br> 
 
<input type="checkbox" name="vehicle" value="Truck"> I have a truck<br>

注: - 代碼開始處理,而不必等待文件加載正確所以基本上它需要要失敗,但是當alert()來的時候它會等待文件被正確渲染,然後你輸出結果。

把整個代碼放在$(document).ready(function(){裏面,你很好去(那麼你也可以刪除alert())。

但更簡單的解決方案是通過me.Thanks

0

HTML代碼:

<input type="checkbox" name='check'> 
    <input type="checkbox" name='check'> 
    <input type="checkbox" name='check'> 
    <input type="checkbox" name='check'> 
    <span id="count"></span> 

JS代碼:

var countChecked = function() { 
var n = $("input:checked").length; 
$("#count").text(n + (n === 1 ? " is" : " are") + " checked!"); 
}; 
    countChecked(); 

$("input[type=checkbox]").on("click", countChecked); 

工作jsfiddle

您可能正在使用js代碼上面的文檔,我刪除了該代碼。

試試看應該有效。

0

隨着警報()這個工作沒有well.But警報(),這不是給我working.How可以修復它

的代碼不會等待DOM準備就緒。 alert()是一個阻塞事件,之後通常會加載DOM。在沒有警報的情況下實現所需功能的一種方式是通過觀察DOM上的DOMContentLoaded事件與.ready()(即$(document).ready())。

$(document).ready(function() { 
 
    var countChecked = function() { 
 
    var n = $("input:checked").length; 
 
    $("#count").text(n + (n === 1 ? " is" : " are") + " checked!"); 
 
    }; 
 

 
    countChecked(); 
 

 
    $("input[type=checkbox]").on("click", countChecked); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div>Count:<span id="count"></span></div> 
 
<div><input type="checkbox" value="1" id="one"><label for="one">1</label></div> 
 
<div><input type="checkbox" value="2" id="two"><label for="one">2</label></div>

0

需要用的document.ready jQuery函數

$(document).ready(function(){ 
    var countChecked = function() { 
    var n = $("input:checked").length; 
    $("#count").text(n + (n === 1 ? " is" : " are") + " checked!"); 
    }; 

countChecked(); 
alert();  // this alert 

$("input[type=checkbox]").on("click", countChecked); 
}) 
包圍你的代碼