桌子里有单选按钮。点击时,我希望相邻的细胞变绿。
我能够使用JQuery在$.change事件上添加一个“突出显示”类来实现这一点。
我的问题是,有时页面已经设置了“选中”属性。当页面加载时,如何使用JQuery定位已经具有“选中”属性的所有单选按钮元素?这是我试过的,但似乎不起作用。
JQUERY
$('input:radio').ready(function() {
if($(this).is(':checked')){
$(this).parent().addClass('highlight');
var $td = $(this).parent();
$td.siblings().removeClass('highlight');
$td.next().addClass('highlight');
}
});CSS
#sort td.highlight {background: #33FF99;}发布于 2014-12-27 08:36:30
要循环遍历所有单选按钮,请使用each函数:
$(document).ready(function(){ $('input:radio').each(function(i,e) { if($(e).is(':checked')){ $(e).parent().addClass('highlight'); var $td = $(e).parent(); $td.siblings().removeClass('highlight'); $td.next().addClass('highlight'); } }); });
发布于 2014-12-27 08:19:20
$(document).ready(function () {
var check = $('input:radio:checked');
if (check.is(':checked')) {
$(check).parent('td').addClass('highlight');
}
$('input:radio').on('change', function () {
$('#sort td').removeClass('highlight');
$(this).parent('td').addClass('highlight');
});
});发布于 2014-12-27 08:28:53
您可以创建一个实用程序函数来突出显示下一个单元格。为表中的每个收音机在document.ready上调用此函数。在每个收音机的change事件上调用相同的函数。
有些事情是这样的:
演示Fiddle: http://jsfiddle.net/abhitalks/tee56wz0/
演示片段
$("input[type=radio]").each(function() {
setHighlight(this); // call the utility function for each radio on document.ready
});
$("input[type=radio]").on("change", function() {
setHighlight(this); // call the utility function for each radio on change
});
function setHighlight(elem) {
if (elem.checked) { // if the radio is checked,
$("table td").removeClass('highlight'); // remove highlight from all cells
$(elem).parent().next().addClass("highlight"); // add highlight to next cell
}
}td.highlight {background: #33FF99;}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
<tr><td><input type="radio" name="common" checked /></td><td>Cell 2</td><td>Cell 3</td></tr>
<tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
<tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
</table>
https://stackoverflow.com/questions/27665546
复制相似问题