【问题标题】:Change class of parent div if radio input checked如果选中无线电输入,则更改父 div 的类
【发布时间】:2012-06-06 05:16:57
【问题描述】:

我一直在用谷歌搜索我的问题的答案,但到目前为止都没有成功。我希望你们中的一个可以给我一些帮助。

Example 已发布HERE。

我的目标是在选择单选时将包含所选单选按钮 className 的表更改为“已选择”,当未选择单选时将其更改为“容器”。

我有 10 个类名为“股息”的 div,其中包含一个类名为“容器”的表,然后是其中的两个较小的表。在底部的容器表中是一个名为“page1”的隐藏单选按钮。然后另外 10 个相同但输入名称为“page2”

我为容器表编写了一个 onClcick,以便用户可以选择整个表而不是单选按钮,但不是我试图更改所选容器的样式,以便用户知道他们已经选择了它。

我尝试了几种不同的方法,只需编写即可将样式更改为新类

 document.getElementById('container').className = 'selected';

但是因为所有 10 个 div 共享相同的名称,它只会改变它找到的第一个元素的样式。

所以我尝试编写这个循环来检查文档中是否有任何选定的收音机,然后将 else 名称更改为默认样式。

我确定这很愚蠢,但我很困惑 atm.. 任何帮助将不胜感激。

谢谢。

//check for check = true
selected = function () {
var divs = document.getElementByTagName('DIV'),
    div,
    tbl = divs.getElementById('TABLE'),
    rad,
    stat,
    i;

    for (var i = 0; i < divs.length; i++) {
// no .id but the counter of the loop
div = div[i];
// check the className not the div element
if (div.className == 'dividend') {

    rad = tbl.getElementsByTagName('INPUT');

    if (tbl.className == 'container') {
    if (rad[0].checked == true) {
        tbl.className = 'selected'; 
    } 
}
}
}
};


// Gets radio button for selected element in Page1 and checks
function P1sClick(n){ 
document.forms["myform"]["page1"][n].checked=true;
selected();
};

// Gets radio button for selected element in Page2 and checks
function P2sClick(n){ 
 document.forms["myform"]["page2"][n].checked=true;

};

////////////HTML  I only included 2 examples of the DIVs because its a lot of code/////

<form name="myform" action="sample.asp" method="POST">

<h2>Page 1</h2>

<div class="dividend>
<table class="container" onclick="P1sClick(0)" cellpadding="0" cellspacing="0"><tr><td valign="top" >
  <table class="grid" cellpadding="0" cellspacing="0">
<tr><td width="40" height="25" style="border-bottom:1px solid #000; border-    right:1px solid #000;">1</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">2</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">3</td></tr>
    <tr><td height="25" style="border-right:1px solid #000;">4</td></tr>
  </table>
</td><td valign="top">
  <table class="grid" cellpadding="0" cellspacing="0">
    <tr><td width="40" height="25" style="border-bottom:1px solid #000;">5</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000;">6</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000;">7</td></tr>
    <tr><td height="25">8</td></tr>
  </table>
</td></tr>
<tr><td colspan="2" align="center" height="20" style="padding-top:3px; font-weight:bold; font-style:italic;">4x4<br><input type="radio" name="page1" title="4 by 4" value="4x4" style="display:none;"></td></tr></table>
</div>

<div class="dividend">
<table class="container" onclick="P2sClick(0)" cellpadding="0" cellspacing="0"><tr><td valign="top">
      <table class="grid" cellpadding="0" cellspacing="0">
    <tr><td width="40" height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">1</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">2</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">3</td></tr>
    <tr><td height="25" style="border-right:1px solid #000;">4</td></tr>
  </table>
</td><td valign="top">
  <table class="grid" cellpadding="0" cellspacing="0">
    <tr><td width="40" height="33" style="border-bottom:1px solid #000;">5</td></tr>
    <tr><td height="33" style="border-bottom:1px solid #000;">6</td></tr>
    <tr><td height="34">7</td></tr>
  </table>
</td></tr>
<tr><td colspan="2" align="center" height="20" style="padding-top:3px; font-weight:bold; font-style:italic;">4x3<br><input type="radio" name="page2" title="4 by 3" value="4x3" style="display:none;"></td></tr></table>
    </div>

更新:

所以我一直在研究 jQuery 并在此处找到 THIS 帖子。我正在尝试这个功能,它看起来应该对我有用,但不是。也许你可以告诉我这是否是一条更好的路线..

$(document).ready(function() {  
$('input[type="radio"]').change( function() {
  //   grab all the radio buttons with the same name as the one just changed
    var this_radio_set = $('input[name="'+$(this).attr("page1")+'"]');

    // iterate through each  
//     if checked, set its parent label's class to "selected"
//     if not checked, remove the "selected" class from the parent label
//     my HTML markup for each button is  <label><input type="radio" /> Label Text</label>
//     so that this works anywhere even without a unique ID applied to the button and label
    for (var i=0; i < this_radio_set.length;i++) {
    if ( $(this_radio_set[i]).is(':checked') )             $(this_radio_set[i]).parent('table').addClass('selected');
        else $(this_radio_set[i]).parent('table').removeClass('selected');
}
});
}); 

更新 我用 BobS 所做的以下更正更新了我的 jQuery。我现在使用 jQuery 通过单击表格来选择单选,并使用 jquery 在选中单选时更改样式。出于某种原因,我在组合这两个功能时遇到了麻烦,所以当您单击表格并选中单选时,样式也会发生变化。这是我最新的代码,希望有人可以帮助我:p

// jQuery to select radio button within clicked table
$(function() {

$('table').click(function(event) {  

    if(event.target.type != "radio") {

        var that = $(this).find('input:radio');
        that.attr('checked', !that.is(':checked'));

    }
});
});

// jQuery to change the style of the table containing the selected radio button
$(function() {
$('input[type="radio"]').change( function() {
  //   grab all the radio buttons with the same name as the one just changed
    var this_radio_set = $('input[name="'+$(this).attr("name")+'"]');

    for (var i=0; i < this_radio_set.length;i++) {
    if ( $(this_radio_set[i]).is(':checked') )         
      $(this_radio_set[i]).closest('table').addClass('selected');
        else 
        $(this_radio_set[i]).closest('table').removeClass('selected');
}
});
});  

【问题讨论】:

  • 您应该编辑您的问题并添加与您使用的语言相对应的标签,以便更快地获得更好的答案。
  • 此示例显示您正在重用 ID,不要这样做,它不是有效的 HTML。一定要多次使用该课程。
  • 对不起,我提交后正在编辑,现在代码已经启动
  • 那么我应该搜索className而不是ID吗?我最近添加了 ID,看看这是否可行..
  • 我很难从描述中找出你想要达到的目标。如果您可以为它创建一个 jsfiddle,我很乐意看一看,看看我是否可以解开它。顺便说一句,整个练习在 jQuery 中会更容易。

标签: javascript loops html radio checked


【解决方案1】:

首先,对于最佳实践,您应该为元素使用不同的 id。 id 是唯一的

第二个错误: if (rad.checked = true) {

它应该带有 == 不只是一个=

【讨论】:

    【解决方案2】:

    我希望我发现了你所有的错误。 X)

    for (var i = 0; i < divs.length; i++) {
        // no .id but the counter of the loop
        div = divs[i];
        // check the className not the div element
        if (div.className == 'dividend') {
            // Next will not work, because you would need divs 
            // with duplicate ids! Use classes instead.
            tbl = div.getElementById('container');
            // getElement>s<ByTagName
            rad = tbl.getElementsByTagName('INPUT');
            // == not =
            if (rad[0].checked == true) {
                tbl.className = 'selected'; 
            } 
        }
    
    }
    

    【讨论】:

    • 我尝试了您对循环所做的更正,但仍然没有任何结果。 :\ 我希望不必为每个表创建唯一的 ID,这样我的脚本可以更高效一些。是否可以检查页面上的所有输入以查看它们是否被检查?
    • 我认为,编写整个 javascript 并在所有浏览器中测试它是没有意义的。你有没有考虑过使用 jQuery 或类似的库?
    • 我不太了解 jQuery,所以我什至不知道从哪里开始。如果你知道任何关于这类事情的好教程,或者你不介意给我一个例子这将是真棒:D
    【解决方案3】:

    一些可能对你有帮助的事情:

    您似乎在最近的编辑中删除了元素的 ID。这很好,但是你必须循环遍历一些东西。您也不应该期望 getElementById 根据元素中的类返回元素;这仅适用于 id。

    但是,在这种情况下,您的“容器”表始终是“股息”div 的直接子级,因此您可以使用诸如

    之类的技术
    tbl=div.childNodes[0];
    

    拿到桌子。

    注意类名比较:如果一个元素有多个类名(通过继承获得),它可能看起来像“fooclass 红利”,然后使用 == 进行字符串比较将不起作用。为此使用正则表达式或字符串拆分。

    我还想重申其他人所说的:停止你正在做的事情并学习 jQuery :-)

    xxstevenxo 提供了一些 jQuery 代码之后的更新:

    我做了 3 件事来让你的新 jQuery 代码做你想做的事情:

    1. 我去掉了“selected”函数的定义,因为它有许多错误导致脚本在遇到示例 jQuery 代码之前退出。也许你没有遇到这个问题——取决于你的 JavaScript 的总和。

    2. 当您参考 $(this).attr("page1") 实际上应该是 $(this).attr("名称") 如果您单击 page1 的单选按钮,这将为您提供“page1”

    3. 使用“最近”而不是“父”。父级仅上升一级,“表”选择器仅用于根据直接父级是否为表进行过滤。最近的继续向上树,直到找到匹配。

    一旦我进行了这 3 项更改,jQuery 所做的事情就会接近您的想法,至少在单击单选按钮时是这样。

    您可能应该在您的“更改”操作中使用该匿名函数并使用它来代替您的“选定”函数,这样样式更改也会在用户单击表格时生效。

    【讨论】:

    • 感谢您的回复,我确实尝试获取股息的 childNode 和/或实际输入的 parentNode,但我没有运气。每当我处理循环时,似乎他们都能胜过我。你知道有什么好的 jQuery 教程/例子吗?
    • 您介意看看我发布的 jQuery 并告诉我这是否是解决此问题的好方法吗?
    • 是的,非常感谢 BobS!我做了你推荐的更正,现在风格改变了,就像我希望的那样。 :D 我明白你在说什么,只有当实际的收音机被点击时它才会改变。我尝试在我的 JS 中选择的函数中编写相同的函数,但这显然不起作用哈哈。我如何在单击表格时选择收音机的 JS 函数中使用这个 jQuery 函数?
    • 我现在工作了一半。我把它贴在 jsfiddle 上给你看。现在我可以点击表格,样式会随着收音机改变,但是当我选择另一个表格时,前一个表格的样式不会变回来..你能看看我的功能,看看我做错了什么吗?这是我正在做的事情。 jsfiddle.net/stevenschemers/cGTYm/2
    • 我能够基于表格的单击获取和删除的样式,但是当检查具有相同名称的另一个收音机时,我似乎无法删除样式.. :|这是我最新的 jsfiddle 的链接 - jsfiddle.net/stevenschemers/cGTYm/20
    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2013-05-27
    • 2017-05-10
    相关资源
    最近更新 更多