zoukankan      html  css  js  c++  java
  • jquery选中radio或checkbox的正确姿势

    jquery选中radio或checkbox的正确姿势

    Intro

    前几天突然遇到一个问题,没有任何征兆的。。,jquery 选中radio button单选框时,一直没有办法选中,后来查了许多资料,发现自己的姿势有问题。

    Issue

    我按下面的方式选中 radio 时,发现有时候会选不中。

      <label class="t-radio t-circle-radio t-green-radio"><input type="radio" value="1" onchange="$('#saleInfo').show()" checked="checked" name="isOnSale" />加入</label>
      <label class="t-radio t-circle-radio t-green-radio"><input type="radio" value="0" onchange="$('#saleInfo').hide()" name="isOnSale" />不加入</label>

    下面是我的 js 代码

        //前面已引用 jquery.js 后文不再赘述
        ...
        $("input[type='radio'][name='isOnSale'][value='1']").attr("checked","checked");

    Solution0

    区分 attribute 和 property

    attribute 和 property 是不同的

    property 是 html 标签固有的属性,而 attribute 多是 html 自定义属性。

    attribute是html文档上标签属性,而 property 则是对应 DOM 元素的自身属性。 从操作方法上来看,attribute可以通过 DOM规范的 getAttributesetAttribute进行获取修改,而property可以通过对象访问属性的方式 . 或者 [" "]来修改获取。 jquery 获取或设置 attribute 用的是 attr ,获取或设置 property 用的是 prop

    Property

    DOM 节点是一个对象,所以它像 JavaScript 的对象一样可以存储自定义的属性和方法。

    Attribute

    DOM节点可以通过以下标准方法访问 HTML 的 attribute

        elem.hasAttribute(name) - checks if the attribute exists
        elem.getAttribute(name) - gets an attribute value
        elem.setAttribute(name, value) - sets an attribute
        elem.removeAttribute(name) - removes an attribute

    checked 是 input 标签的属性(property)而不是 attribute ,参见 http://www.w3school.com.cn/tags/att_input_checked.asp

    更多 input 相关的属性详见: http://www.w3school.com.cn/tags/tag_input.asp

    Solution1

    HACK:mock click

    设置选中之后调用对象的click()方法,模拟点击

        //toogle
        $("input:radio[name='isOnSale'][value='1']").click();

    Solution2

    设置 input 的 checked 属性

    原生js

        //check
        document.getElementsByName("isOnSale")[0].checked = true;
        //uncheck
        document.getElementsByName("isOnSale")[0].checked = false;

    jquery

        //
        $("input[type='radio'][name='isOnSale'][value='1']").prop("checked",true);

    More

    如果你有别的更好的解决方案,欢迎指出。

    如果有什么问题,欢迎联系我 ben121011@126.com

  • 相关阅读:
    Largest Submatrix of All 1’s
    Max Sum of Max-K-sub-sequence
    Sticks Problem
    Splay模版
    B. Different Rules
    链表合并 leetcode
    K个一组翻转链表
    反转链表2 leetcode
    nodejs简单仿apache页面
    HTML 5 Web Workers
  • 原文地址:https://www.cnblogs.com/weihanli/p/6292797.html
Copyright © 2011-2022 走看看