1. 程式人生 > >jQuery操作複選框狀態

jQuery操作複選框狀態

jQuery操作複選框狀態

在很多專案中,我們通常需要使用者同意相關協議,才可以進行某種操作;在這種場景下,我們需要獲取複選框的checked屬性,才可以正確的執行判斷。


程式碼結構

HTML檔案
<div class="tips">
	<input type="checkbox" />
	<a href="privacyPolicy.html">我已閱讀並同意《
		<span>使用者協議和隱私條款</span></a>
</div>

CSS檔案
.tips {
font-size: 28px; margin-top: -30px !important; margin-bottom: 30px; line-height: 80px; >input[type="checkbox"]{ width: 37px; height: 37px; vertical-align: middle; border-radius: 50%; margin-right: 10px;
margin-left: 10px; cursor: pointer; } >a { text-decoration: none; color: #000000; vertical-align: middle; >span { border-bottom: 3px solid #3196DA; } }

JS檔案
	// 複選框選中觸發的事件
$(".tips input[type='checkbox']").click(function() { if($(this).prop("checked")) { $(this).prop("checked", true); console.log("AAAA",$(this).prop("checked")); console.log("選中了!!!!!"); } else { $(this).prop("checked", false); console.log("BBBB",$(this).prop("checked")); console.log("對不起,沒選中"); } })

使用介紹

通過程式碼中的 $(this).prop(“checked”) ,我們可以獲取對應的複選框的checked屬性,其返回的結果是 true / false;在需要做判斷的地方,我們利用布林值 $(this).prop(“checked”) 即可。