2014-03-31 75 views
1

從以前的線程我已經使用了下面的代碼。綁定切換按鈕onClick到div

當前代碼可在審覈http://jsfiddle.net/sLHKq/

<div id="question1"> 
<ol> 
<li id="correct1">A1</li> 
<li id="">A2</li> 
</ol> 
<div id="answer1" style="display:none;"></div> 
<button onclick="toggle('answer1');">Button 1</button> 
</div> 
<hr> 
<div id="question2"> 
<ol> 
<li id="">B1</li> 
<li id="correct2">B2</li> 
</ol> 
<div id="answer2" style="display:none;"></div> 
</div> 
<button onclick="toggle('answer2');">Button 2</button> 

我使用的JavaScript是對的OnClick correct1如下,correct2 ID在這兩個div的是變化的背景color.I嘗試這種代碼去實現它只有各自的按鈕的切換工作。

function toggle(id) { 
var e = document.getElementById(id); 
if (e.style.display == 'none') { 
e.style.display = 'block'; 
document.getElementById("correct1").style.backgroundColor = '#BCF5A9'; 
document.getElementById("correct2").style.backgroundColor = '#BCF5A9'; 

} else { 
e.style.display = 'none'; 
document.getElementById("correct1").style.backgroundColor = '#FFFFFF'; 
document.getElementById("correct2").style.backgroundColor = '#FFFFFF'; 

} 
} 

如何限制onclick和背景顏色變化只是問題的按鈕div?

回答

1

你的意思是這樣的:

function toggle(id) { 
    var e = document.getElementById("answer" + id); 
    if (e.style.display == 'none') { 
     e.style.display = 'block'; 
     document.getElementById("correct" + id).style.backgroundColor = '#BCF5A9'; 
     document.getElementById("correct" + id).style.backgroundColor = '#BCF5A9'; 

    } else { 
     e.style.display = 'none'; 
     document.getElementById("correct" + id).style.backgroundColor = '#FFFFFF'; 
     document.getElementById("correct" + id).style.backgroundColor = '#FFFFFF'; 

    } 
} 

查看更新Fiddle

+0

感謝@Sudhir代碼更新,出於某種原因時我把這個更新後的代碼放在我的本地主機上。它表示Uncaught TypeError:無法在'document.getElementById(「correct」+ id).style.backgroundColor'處讀取屬性'style'null。 任何想法可能是什麼原因。 – Avil

+0

@Avil,這將意味着代碼無法找到相關的ID,檢查您的ID是否存在.. –

+0

謝謝,我在測試時得到了錯誤。我發現如果在question2 div中添加新的id = correct1。該代碼添加它只突出顯示correct2。 如果在不同的問題div中有不同的id = correct1,id = corect2組合,它是否需要創建具有不同參數的多個函數? Question1 div只有id = correct1 Question2有ids correct1和correct2 請指教。 – Avil

0

我建議也通過正確的答案編號在這樣的功能:

function toggle(id, ans) { 
    var e = document.getElementById(id); 
    if (e.style.display == 'none') { 
     e.style.display = 'block'; 
     document.getElementById(ans).style.backgroundColor = '#BCF5A9'; 
    } else { 
     e.style.display = 'none'; 
     document.getElementById(ans).style.backgroundColor = '#FFFFFF'; 
    } 
} 

檢查小提琴:http://jsfiddle.net/sLHKq/2/