【问题标题】:Using javascript onClick to style currently selected radio button使用 javascript onClick 设置当前选定单选按钮的样式
【发布时间】:2012-05-25 01:49:56
【问题描述】:

我正在尝试将“当前”类添加到当前选择的任何单选选项中。我可以使用

onClick="document.getElementById('volunteering').class += 'current';"

但是,这确实会添加类,但是当您选择另一个单选按钮时它会粘住(因为它位于每个按钮上)。关于如何在所有单选按钮上实现它的任何想法?

这是我正在使用的代码:

<form> 
<ul>
    <input type="radio" name="category" id="volunteering" value="volunteering"><li class="conversation">
   <a href="#" onClick="document.getElementById('volunteering').checked = true;" >Volunteering</a>
 </li>
 <input type="radio" name="category" value="cityproblems" id="cityproblems"><li class="conversation">
   <a href="#" onClick="document.getElementById('cityproblems').checked = true;" >City Problems</a>
  </li>
 <input type="radio" name="category" value="safety" id="safety"><li class="conversation">
    <a href="#" onClick="document.getElementById('safety').checked = true;" class="">Safety</a>
 </li>
</form>

【问题讨论】:

    标签: javascript forms radio-button


    【解决方案1】:

    您需要首先从所有单选按钮中删除该类,然后将其添加回单击的单选按钮。定义一个函数,通过接收 id 作为参数来执行此操作,并将其绑定到 onclick

    function selectRadioClass(radioId) {
      // Note - there are more clever ways, like arrays and loops
      // for this, but if it's only 3, this is fine
      document.getElementById('volunteering').className = '';
      document.getElementById('cityproblems').className = '';
      document.getElementById('safety').className = '';
    
      // Then add it back to the node passed in by id
      document.getElementById(radioId).className = 'current';
      // And check the button
      document.getElementById(radioId).checked = true;
    }
    

    然后绑定每个单选按钮的onclick 使用:

    <a href="#" onClick="selectRadioClass('safety');" class="">Safety</a>
    

    【讨论】:

      【解决方案2】:

      有两种解决方案:

      使用 CSS3 :checked 选择器

       form input:checked {
         /* your style rules here. */
         /* No more scripting needed. */
       }
      

      http://www.quirksmode.org/css/enabled.html

      为此目的使用全局函数。

      //检查迈克尔的解决方案。

      【讨论】:

        【解决方案3】:

        使用 CSS 伪选择器并忘记 JavaScript。 element:checked 有一个。

        http://css-tricks.com/pseudo-class-selectors/

        【讨论】:

          猜你喜欢
          • 2013-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-06
          • 1970-01-01
          • 2017-10-25
          • 2021-02-14
          • 2016-03-01
          相关资源
          最近更新 更多