我有以下功能,如何使用jquery简化它?
function updateCards(){
var form = document.getElementById("sets");
var chks = form.querySelectorAll('input[type="checkbox"]');
var checked = [];
for(var i = 0; i < chks.length; i++){
if(chks[i].checked){
checked.push(chks[i].value)
}
}
// test code
//alert("SELECTED SETS:"+checked);
if (checked == ""){
document.getElementById("all-cards").innerHTML = "";
return;
}
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("all-cards").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_cards.php?sets="+checked, true);
xmlhttp.send();
}
答案 0 :(得分:1)
尝试
function updateCards(){
var $form = $('#sets'), $chks = $form.find('input:checkbox'), checked ;
checked = $chks.map(function(){
return this.checked ? this.value : undefined;
}).get();
if (checked.length == 0){
$('#all-cards').html('');
return;
}
$.ajax({
url: 'update_cards.php',
type: 'GET',
data: {
sets: checked
},
dataType: 'html'
}).done(function(html){
$('#all-cards').html(html);
})
}
答案 1 :(得分:1)
jQuery中的相同功能可以写成如下所示。
function updateCards() {
var $form = $('#sets'),
$chks = $('input[type="checkbox"]:checked'),
$allCards = $('#all-cards');
var checked = $chks.map(function() {
return this.value
});
if(checked.length === 0) {
$allCards.html('');
return
}
// Ajax
$.ajax({
url : "update_cards.php?sets="+checked,
type: 'get',
dataType: 'html'
}).done(function(data) {
$allCards.html(data);
}).fail(function(xhr, status, error) {
console.log(error);
});
}