zoukankan      html  css  js  c++  java
  • 以checked选中作为判断条件的各种写法

    <input type="radio" name="choice" id="ipt1">
    <label for="ipt1">弹出1</label>
    <input type="radio" name="choice" id="ipt2">
    <label for="ipt2">弹出2</label>
    <input type="button" value="确定" id="confirm">

    首先参考attr与prop的区别:

    attr 读取DOM节点属性,当页面渲染完,checked属性就确定了。

    prop 读取HTML元素属性,checked属性可以改变。

    以下为错误示例:

    //错误:使用attr判断,在上面的html中未选中,得到的是false;
    $('#confirm').click(function(){
        if($('#ipt1').attr('checked')){
             alert(1);
        }else{
             alert(2);
        }
    });
    
    //错误:JS与jquery混写,jQuery中没有.checked属性,得到的是false;
    $('#confirm').click(function(){
        if($('#ipt1').checked){
             alert(1);
        }else{
             alert(2);
        }
    });
    
    //错误:判断的是jQuery中$('#ipt1:checked')选择器是否存在,得到的是true;
     $('#confirm').click(function(){
        if($('#ipt1:checked')){
             alert(1);
        }else{
             alert(2);
        }
    });

    以下为正确示例:

    //正确:jQuery用is方法传入:checked伪类选择器。
     $('#confirm').click(function(){
        if($('#ipt1').is(":checked")){
             alert(1);
        }else{
             alert(2);
        }
    });
    
    //正确:用prop读取HTML元素属性。
    $('#confirm').click(function(){
        if($('#ipt1').prop('checked')){
             alert(1);
        }else{
             alert(2);
        }
    });
    
    //正确:JS写法。  
    var confirm=document.getElementById('confirm');
    confirm.onclick = function(){
        var oIpt1=document.getElementById('ipt1');
        if(oIpt1.checked == true){
            alert(1);
        }else{
             alert(2);
        }
    };
  • 相关阅读:
    filter过滤器(转载)
    匿名函数 lambda
    偏函数(转载)
    python中的多重继承和Mixin(转载)
    __slot__
    virtual hust 2013.6.21 NEFU 挑战编程----数论 E
    virtual hust 2013.6.21 NEFU 挑战编程----数论 D
    virtual hust 2013.6.21 NEFU 挑战编程----数论 C
    virtual hust 2013.6.21 NEFU 挑战编程----数论 B
    virtual hust 2013.6.21 NEFU 挑战编程----数论 A
  • 原文地址:https://www.cnblogs.com/nicoleyani/p/5956259.html
Copyright © 2011-2022 走看看