我在一个 div 中有一些复选框,这些复选框受其中的数字限制data-max-answers
(从 Wordpress 中获取)。因此,如果该数字为 2,则用户只能勾选其中的 2 个复选框,而其他复选框为灰色。
我遇到的问题是我无法弄清楚如何深入研究 div 以定位复选框,有人可以帮我吗?
我有一个简化版本,其中复选框直接位于 div 中,这工作正常,但无法让它在嵌套 div 的地方工作 - http://jsfiddle.net/pVA3d/4/。
<div class="question" data-max-answers="<?php echo $repeater_row['required_answers']; ?>">
<?php $rows = $repeater_row['answer_options'];
foreach ($rows as $row){ ?>
<?php $Question[$counter] = $_POST['answer'.$counter]; ?>
<div style="display:table-row;">
<div style="display:table-cell;">
<input style="width: 20px;" type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
</div>
<div style="display:table-cell;">
<p>
<?php echo $row['answer']; ?>
</p>
</div>
</div>
<?php } ?>
</div>
查询:
jQuery(function($) {
$(document).ready(function () {
$("input[type=checkbox]").click(function (e) {
if ($(e.currentTarget).closest("div.question").length > 0) {
toggleInputs($(e.currentTarget).closest("div.question")[0]);
}
});
});
});
jQuery(function($) {
function toggleInputs(questionElement) {
if ($(questionElement).data('max-answers') == undefined) {
return true;
} else {
maxAnswers = parseInt($(questionElement).data('max-answers'), 10);
if ($(questionElement).find(":checked").length >= maxAnswers) {
$(questionElement).find(":not(:checked)").attr("disabled", true);
} else {
$(questionElement).find("input[type=checkbox]").attr("disabled", false);
}
}
}
});