我在jQuery中使用on()方法,我想知道是否可以縮短我的代碼,因爲我只是一遍又一遍地使用代碼,但使用不同的子選擇器。 是否可以在一個on()
中使用多個子選擇器?在多個子選擇器on()Javascript
這是一個示例代碼,我有很多這樣的代碼。
$(document.body).on('change', 'input[name*="create"]', function() {
var $class = $(this).attr('class');
if (!$(this).is(':checked')) { //not checked
$('input[name*="' + $class + '_selectall"]').attr({
'checked': false
});
} else {
$('input[name*="' + $class + '_selectall"]').attr({
'checked': true
});
}
});
$(document.body).on('change', 'input[name*="compute"]', function() {
var $class = $(this).attr('class');
if (!$(this).is(':checked')) { //not checked
$('input[name*="' + $class + '_selectall"]').attr({
'checked': false
});
} else {
$('input[name*="' + $class + '_selectall"]').attr({
'checked': true
});
}
});
$(document.body).on('change', 'input[name*="print"]', function() {
var $class = $(this).attr('class');
if (!$(this).is(':checked')) { //not checked
$('input[name*="' + $class + '_selectall"]').attr({
'checked': false
});
} else {
$('input[name*="' + $class + '_selectall"]').attr({
'checked': true
});
}
});
我想知道是否有可能使用多個'input[name*="create"]'
在一個on()
,這樣我就不必重複了。
爲什麼不只是創建一個函數而不是重複匿名函數3次? – devzero
''input [name * =「create」],input [name * =「compute」],input [name * =「print」]'',或者更好的是使用一個類。 –
'$ class'是一個字符串,而不是'$'jQuery對象引用,所以使用'klass' :) –