紅糖糍粑
2019-12-09 09:35:10
如果該復選框已選中,那么我只需要將值設為1;否則,我需要將其設置為0。如何使用jQuery?$("#ans").val() 在這種情況下,總是會給我一項權利:<input type="checkbox" id="ans" value="1" />
3 回答

慕運維8079593
TA貢獻1876條經(jīng)驗 獲得超5個贊
$("#ans").attr('checked')
會告訴您是否已檢查。您還可以使用第二個參數(shù)true / false來選中/取消選中該復選框。
$("#ans").attr('checked', true);
根據(jù)評論,使用prop而不是attr可用時。例如:
$("#ans").prop('checked')

ABOUTYOU
TA貢獻1812條經(jīng)驗 獲得超5個贊
Stefan Brinkmann的答案很好,但對于初學者來說還不完整(省略了變量分配)。只是澄清一下:
// this structure is called a ternary operator
var cbAns = ( $("#ans").is(':checked') ) ? 1 : 0;
它是這樣的:
var myVar = ( if test goes here ) ? 'ans if yes' : 'ans if no' ;
例:
var myMath = ( 1 > 2 ) ? 'yes' : 'no' ;
alert( myMath );
警報“否”
如果這有幫助,請支持Stefan Brinkmann的答案。
添加回答
舉報
0/150
提交
取消