Ok, this code works fine
<html>
<body>
<p>This is question.</p>
<img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42"
width="42" id="showHideImg" onclick="myFunction()">
<p id="showHide">This answer.</p>
<script type="text/javascript">
function myFunction() {
if (document.getElementById("showHide").style.display=="none")
{
document.getElementById("showHide").style.display="block";
}
else
{
document.getElementById("showHide").style.display="none";
}
}
</script>
</body>
</html>
However, in the real app, I got many images & <p> like the followings:
<p>This is question1.</p>
<img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42"
width="42" id="showHideImg" onclick="myFunction()">
<p id="showHide1">This answer1.</p>
<p>This is question2.</p>
<img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42"
width="42" id="showHideImg" onclick="myFunction()">
<p id="showHide2">This answer2.</p>
.......question 3... 4....5...
My question is that how to modify the myFunction() so that it can dynamically apply for many images
I tried like the following:
<p>This is question1.</p>
<img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42"
width="42" id="showHideImg" onclick="myFunction(1)">
<p id="showHide1">This answer1.</p>
<script type="text/javascript">
function myFunction(var no) {
if (document.getElementById("showHide"+no).style.display=="none")
{
document.getElementById("showHide"+no).style.display="block";
}
else
{
document.getElementById("showHide"+no).style.display="none";
}
}
But it doesn't work
2 Answers 2
You don't need var when declaring your method arguments.
Try the following:
function myFunction(no) {
if (document.getElementById("showHide"+no).style.display=="none")
{
document.getElementById("showHide"+no).style.display="block";
}
else
{
document.getElementById("showHide"+no).style.display="none";
}
}
answered Jan 20, 2016 at 17:46
crmpicco
17.3k32 gold badges142 silver badges224 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Just pass it in, leave off the var, and you're done.
I'd refactor out a bunch of stuff though, and make names meaningful, e.g.,
function toggleEl(num) {
var el = document.getElementById("showHide" + num)
, currStyle = el.style.display
, nextStyle = curr === "none" ? "block" : "none"
;
el.style.display = nextStyle;
}
(Note that toggle() may be sufficient for your ultimate needs.)
answered Jan 20, 2016 at 17:50
Dave Newton
161k27 gold badges264 silver badges311 bronze badges
Comments
default
var. You should only haveno, notvar no.