代码之家  ›  专栏  ›  技术社区  ›  bdl

单选按钮开/关触发器只能单向工作

  •  1
  • bdl  · 技术社区  · 15 年前

    所以这是我一段时间以来最愚蠢的事情。我无法设置简单单选按钮的状态来切换页面上的某些内容。

    <label for="completeSw"><span>Completed?</span></label>
    <input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
    <input type="radio" id="completeSw" name="completeSw" value="0" checked="checked"/>No<br/>
    

    默认状态为“否”;如果单击“是”,则可以检索onchange或onclick事件状态并使其发生。但是,这是一个单向开关;一旦转到“是”,我就无法检索返回“否”选择器的状态。我需要做的是根据他们在这台收音机中所做的选择在页面上显示/隐藏一个元素。如果单击“是”,我可以触发该操作并查看页面更改。但是,一旦我单击“否”,它就好像没有状态更改一样,我无法执行操作,即再次隐藏元素。

    我尝试过检索“checked”状态、无线电对值等变量,例如。

    $("#completeSw").change(function(e){
        alert( $(this).attr("checked") ); // only triggers when "Yes" is selected
    });
    

    也许我不应该使用yes/no单选对,而应该使用单个复选框?在我看来,这种方式(单选按钮)更加友好和优雅。

    4 回复  |  直到 15 年前
        1
  •  4
  •   Diodeus - James MacFarlane    15 年前

    ID必须是唯一的,所以它只能在页面上找到第一个ID。改为使用类。

        2
  •  3
  •   Bick    15 年前

    <label for="completeSw"><span>Completed?</span></label>
    <input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
    <input type="radio" name="completeSw" value="0" checked="checked"/>No<br/>
    

    你将处理 checked 仅此元素的属性。对-“是”,错-“否”

        3
  •  0
  •   cutsoy    15 年前

    有些浏览器在alert(message),message=null时不执行任何操作。由于未选中的字段没有选中的属性,所以可能是这样的:)。

    尝试:

    alert('Checked: '+$(this).attr("checked"));
    
        4
  •  0
  •   Sandro    15 年前

    <span>Completed?</span>
    <input type="radio" id="completeSwYes" name="completeSw" value="1"/><label for="completeSwYes">Yes</label>
    <input type="radio" id="completeSwNo" name="completeSw" value="0" checked="checked"/><label for="completeSwNo">No</label><br/>
    
    <script type="text/javascript" charset="utf-8">
        // If the radio button value is one then this evaluates to true.
        var completeSW;
        jQuery("input[type='radio'][name='completeSw']").change(function() {
            completeSW = (jQuery(this).val() == 1);
            alert("completeSW checked? " + completeSW);
        });
    </script>