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規范的 getAttribute
和 setAttribute
進行獲取修改,而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
文章列表