n個div,每個div裡都有一個單選按鈕, 效果:1、**點擊第一個div**,單選被選中(單選框用圖片代替),再次點擊第一個div,單選被取消;2、同時,點擊第二個div時,單選被選中,第一個div的單選被取消;
<div onclick="clickDiv(this)"><input id="radio1" type="radio" value="1" />Value 1</div>
<div onclick="clickDiv(this)"><input id="radio2" type="radio" value="2" />Value 2</div>
<div onclick="clickDiv(this)"><input id="radio3" type="radio" value="3" />Value 3</div>
<div onclick="clickDiv(this)"><input id="radio4" type="radio" value="4" />Value 4</div>
<div onclick="clickDiv(this)"><input id="radio5" type="radio" value="5" />Value 5</div>
<div onclick="clickDiv(this)"><input id="radio6" type="radio" value="6" />Value 6</div>
<script type="text/javascript">
var lastRadio;
var lastAction;
var allRadio = [];
//初始化獲得到所有單選鈕
(function(){
var allInput = document.getElementsByTagName("input");
for(var i=0;i<allInput.length;i++){
if(allInput[i].type=="radio"){
allRadio.push(allInput[i]);
}
}
}());
//當DIV被點擊時觸發
function clickDiv(divObj){
var obj = divObj.children[0];
obj.checked = true;
for(var i=0;i<allRadio.length;i++){
if(obj.id == allRadio[i].id){
var currRadio = document.getElementById(obj.id);
if(currRadio == lastRadio & lastAction){
currRadio.checked = false;
}
lastRadio = currRadio;
lastAction = currRadio.checked;
}else{
document.getElementById(allRadio[i].id).checked = false;
}
}
}
</script>