我有一个jQuery函数,我需要循环使用两个变量,我需要增加到一定数量。这是功能:
var i = 1;
var x = 13;
$('input#question14_' + i).change(function() {
if (this.checked) {
$('.quiz_section.question-section-id-' + x).css('display', 'block')
} else {
$('.quiz_section.question-section-id-' + x).css('display', 'none')
}
});
我需要i
转到15
和x
转到28
然后停止。显然,我不想为每个数字写出这样的函数,但是我无法弄清楚如何增加这两个函数并循环遍历。
答案 0 :(得分:2)
理想情况下,我会说尝试使用数据元素,因此您可以拥有一个事件处理程序。这样每个元素都可以包含data-id="1"
和data-other="13"
。但是,您可以从ID中提取并生成x
。
//find all the elements who's id begins with question14_
$('input[id^="question14_"]').change(function() {
//get the number after the _ and add 12
var x = parseInt(this.id.split('_')[1], 10) + 12;
if (this.checked) {
$('.quiz_section.question-section-id-' + x).css('display', 'block')
} else {
$('.quiz_section.question-section-id-' + x).css('display', 'none')
}
});