如何检查单选按钮是否具有属性'checked'与原型

How do you check if a radio button has the attribute 'checked' with Prototype

本文关键字:属性 checked 原型 何检查 检查 是否 单选按钮      更新时间:2023-09-26

我有一些代码检查列表,如果LI标签包含单选按钮输入的。我有一些聪明的逻辑通过Chocolate Chip Javascript框架库来计算,当一个LI被点击时,它将应用一个相关的类来显示单选按钮已被选中。

但是,我想扩展该逻辑,以便它更深入地挖掘LI,并在页面加载时发现哪个单选按钮输入是已经选择的(在任何用户选择任何内容之前),并对其应用一个类,以便它立即突出显示已经选择的内容。

我对原型有点陌生,所以我不确定什么是最好的方法,所以我会感谢您可以提供的任何帮助。

在下面的例子中,我想选择按钮3

JSFiddle链接:http://jsfiddle.net/Qw6KA/

HTML:

<ul class="radioList">
   <li>
      <input type="radio" id="radio1" name="radioButton" value="Button 1">
      <label for="radio1">Button 1</label>
   </li>
   <li>
      <input type="radio" id="radio2" name="radioButton" value="Button 2">
      <label for="radio2">Button 2</label>
   </li>
   <li>
      <input type="radio" id="radio3" name="radioButton" value="Button 3" checked="checked">
      <label for="radio3">Button 3</label>
   </li>
   <li>
      <input type="radio" id="radio4" name="radioButton" value="Button 4">
      <label for="radio4">Button 4</label>
   </li>
</ul>

JS(原型):

$.RadioButtons = function( viewSelector, callback ) {
    var items = viewSelector + ".radioList li";
    var radioButtons = $$(items);
    radioButtons.forEach(function(item) {
        item.bind("click", function() {
            radioButtons.forEach(function(check) {
                check.removeClass("selected");
            });
            this.addClass("selected");
            this.last().checked = true; 
            if (callback) {
                callback(item);
            }
        });
    });
};

谢谢-JaXL

$.RadioButtons = function( viewSelector, callback ) {
    var items = viewSelector + ".radioList li";
    var radioButtons = $$(items);
    radioButtons.forEach(function(item) {
        item.bind("click", function() {
            radioButtons.forEach(function(check) {
                check.removeClass("selected");
            });
            this.addClass("selected");
            this.last().checked = true; 
            if (callback) {
                callback(item);
            }
        });
        // Add this bit
        if (item.select('input[checked]').length) {
            item.addClassName('selected');
        }
    });
};