給radio加本身的樣式(圖片)

$('.choice').click(function() {
var display1 = $("#check").prop("checked");
console.log(display1);
if (display1) {
console.log(111)
$('#icons').prop("style", "display:block");
$("#check").prop('checked', false);

} else {
console.log(222)
$('#check').prop("style", "display:block");
$("#check").prop('checked', true);
}
});
 
<div class="choice">
<!-- 這邊是沒有點擊的圈 -->
<input name="choice" type="radio" class="radio" id="check" checked="">
<!-- 這邊是點擊的圈 -->
<label for="a" class="radio" id="icons"></label>
</input>
</div>
 
/* 單選框默認樣式隱藏*/
 
.radio {
background: url('./images/18c9b919b850fd39d9cf897609801e8.png') no-repeat;
height: .3rem;
width: .3rem;
background-size: contain;
}
 
input[type='radio'].radio:checked+.radio {
height: .3rem;
width: .3rem;
background: url('./images/5a5545563b8da60d099ff706f0dca81.png') no-repeat;
background-size: contain;
}
 
label {
width: .3rem;
height: .3rem;
}
 這裏遇到的坑就是prop和attr的區別

jquery中attr和prop的區別

 

在高版本的jquery引入prop方法後,何時該用prop?何時用attr?它們兩個之間有什麼區別?這些問題就出現了。html

關於它們兩個的區別,網上的答案不少。這裏談談個人心得,個人心得很簡單:jquery

  • 對於HTML元素自己就帶有的固有屬性,在處理時,使用prop方法。
  • 對於HTML元素咱們本身自定義的DOM屬性,在處理時,使用attr方法。

 

上面的描述也許有點模糊,舉幾個例子就知道了。 post

<a href="http://www.baidu.com" target="_self" class="btn">百度</a>

 這個例子裏<a>元素的DOM屬性有「href、target和class",這些屬性就是<a>元素自己就帶有的屬性,也是W3C標準裏就包含有這幾個屬性,或者說在IDE裏可以智能提示出的屬性,這些就叫作固有屬性。處理這些屬性時,建議使用prop方法。url

<a href="#" id="link1" action="delete">刪除</a>

這個例子裏<a>元素的DOM屬性有「href、id和action」,很明顯,前兩個是固有屬性,然後面一個「action」屬性是咱們本身自定義上去的,<a>元素自己是沒有這個屬性的。這種就是自定義的DOM屬性。處理這些屬性時,建議使用attr方法。使用prop方法取值和設置屬性值時,都會返回undefined值。code

 

再舉一個例子:htm

<input id="chk1" type="checkbox" />是否可見
<input id="chk2" type="checkbox" checked="checked" />是否可見

像checkbox,radio和select這樣的元素,選中屬性對應「checked」和「selected」,這些也屬於固有屬性,所以須要使用prop方法去操做才能得到正確的結果。blog

$("#chk1").prop("checked") == false
$("#chk2").prop("checked") == true

若是上面使用attr方法,則會出現:rem

$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"
相關文章
相關標籤/搜索