作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 php 数组,我试图让 jQuery 来检查这些复选框,但我似乎无法让它工作。我的 php 数组名称是“toCheck”,即:
Array
(
[0] => 0
[1] => 3
[2] => 4
)
0,3,4 是我需要检查的复选框。这是我的复选框:
<input type="checkbox" name="correct[0]" id="correct" value="0" />
<input type="checkbox" name="correct[1]" id="correct" value="1" />
<input type="checkbox" name="correct[2]" id="correct" value="2" />
<input type="checkbox" name="correct[3]" id="correct" value="3" />
<input type="checkbox" name="correct[4]" id="correct" value="4" />
<input type="checkbox" name="correct[5]" id="correct" value="5" />
如果有人能指出使用什么 jQuery 来选中这些复选框,那就太好了!
<?php foreach($toCheck as $checkMe) { ?>
//i'm assuming my jquery goes here but I can't get it working
<?php }; ?>
提前谢谢你:)
最佳答案
您的 HTML 无效。 id
值在文档 ( reference ) 中必须唯一。
也就是说,忽略 id
值,您可以使用这个( live example ):
$(':checkbox[name^=correct]').each(function() {
switch (this.value) {
case "0":
case "3":
case "4":
this.checked = true;
break;
}
});
它在 name
属性上使用 CSS3 子字符串选择器(jQuery 支持几乎所有 CSS3)来选择名称以 Correct
开头的任何复选框,然后使用 jQuery each
循环遍历它们。然后我们在具有所需值
的属性上设置checked
属性。
您也可以使用更长的选择器而不使用循环( live example ):
$(':checkbox[name^=correct][value=0], :checkbox[name^=correct][value=3], :checkbox[name^=correct][value=4]').attr('checked', true);
更新:重新阅读您的问题,看起来您可能需要更动态地执行此操作:
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
<?php foreach($toCheck as $checkMe) { ?>
echo "boxes.add(':checkbox[name=^=correct][value=" . $toCheck . "]');";
<?php }; ?>
boxes.attr('checked', true);
})();
</script>
...这会生成:
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
boxes.add(':checkbox[name=^=correct][value=0]');
boxes.add(':checkbox[name=^=correct][value=3]');
boxes.add(':checkbox[name=^=correct][value=4]');
boxes.attr('checked', true);
})();
</script>
...这将检查相关的框。但它不会非常有效(所有文档遍历),最好使用 PHP 将值组合到选择器或 switch
中,如上所示。
关于php - 使用 jquery 检查 php 数组中的复选框需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393468/
我是一名优秀的程序员,十分优秀!