天天看點

js實作checkbox全選、不選與反選

本文執行個體講述了js實作checkbox全選、不選與反選的方法。分享給大家供大家參考。具體分析如下:

一、思路:

1. 擷取元素

2. 給全選 不選 反選添加點選事件

3. 用for循環checkbox

4. 把checkbox的checked設定為true即實作全選

5. 把checkbox的checked設定為false即實作不選

6. 通過if判斷,如果checked為true選中狀态的,就把checked設為false不選狀态,如果checked為false不選狀态的,就把checked設為true選中狀态。

二、html代碼:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

<

input

type

=

"button"

value

=

"全選"

id

=

"sele"

/>

<

input

type

=

"button"

value

=

"不選"

id

=

"setinterval"

/>

<

input

type

=

"button"

value

=

"反選"

id

=

"clear"

/>

<

div

id

=

"checkboxs"

>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

<

input

type

=

"checkbox"

/><

br

/>

</

div

>

三、js代碼:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

<script>

window.onload=

function

(){

var

sele=document.getElementById(

'sele'

);

//擷取全選

var

unsele=document.getElementById(

'setinterval'

);

//擷取不選

var

clear=document.getElementById(

'clear'

);

//擷取反選

var

checkbox=document.getElementById(

'checkboxs'

);

//擷取div

var

checked=checkbox.getElementsByTagName(

'input'

);

//擷取div下的input

//全選

sele.onclick=

function

(){

for

(i=0;i<checked.length;i++){

checked[i].checked=

true

}

}

//不選

unsele.onclick=

function

(){

for

(i=0;i<checked.length;i++){

checked[i].checked=

false

}

}

//反選

clear.onclick=

function

(){

for

(i=0;i<checked.length;i++){

if

(checked[i].checked==

true

){

checked[i].checked=

false

}

else

{

checked[i].checked=

true

}

}

}

}

</script>

希望本文所述對大家的javascript程式設計有所幫助

轉載于:https://www.cnblogs.com/keringing/p/7561291.html

繼續閱讀