Can not get the javascript "show hide" div code to work
I CANNOT use jQuery on this project (开发者_运维问答client policy).
My html code is:
<div style="display:none" id="dvAnswer<%#Eval("num")%>" class="TextFontBold">A: <%#Eval("answer") %></div>
<a id="btn<%#Eval("num")%>" href="javascript:toggle();">show answer</a>
Javascript code is:
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
I cannot get this code to work.
Any suggestions to resolving this?Here you need to pass two references to your toggle function, one to the target, and one to itself:
<div style="display:none" id="dvAnswer<%#Eval("num")%>" class="TextFontBold">A: <%#Eval("answer") %></div>
<a id="btn<%#Eval("num")%>" href="javascript://" onclick="toggle('dvAnswer<%#Eval("num")%>',this);">show answer</a>
(plus, it's is good practice to use onclick
, not href
for inline javascript)
Then pass these references to your function:
function toggle(target,me) {
var ele = document.getElementById(target);
var text = me
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
The ID of your element is not toggleText and I don't see an displayText element either.
First your div doesn't have id="toggleText" and no id="displayText"
so what you need to do is create small algorithm for that
function toggle(lnk) {
var num = lnk.getAttribute('id').toString().replace('btn','');
var ele = document.getElementById('dvAnswer'+num);
if(ele.style.display == "block") {
ele.style.display = "none";
lnk.innerHTML = "show";
}
else {
ele.style.display = "block";
lnk.innerHTML = "hide";
}
}
and your html should look like this
<div style="display:none" id="dvAnswer<%#Eval("num")%>" class="TextFontBold">A: <%#Eval("answer") %></div>
<a id="btn<%#Eval("num")%>" onclick="toggle(this); return false;" href="#">show answer</a>
It appears you are calling elements by the wrong IDs. In your HTML, I do not see 'toggleText' or 'displayText' IDs for any of your elements.
The ID looks dynamic from your example. Perhaps just pass the object reference in your function:
function toggle(objRef) {
var ele = document.getElementById(objRef);
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
And HTML of:
<a id="btn<%#Eval("num")%>" href="javascript:toggle("dvAnswer<%#Eval("num")%>");">show answer</a>
Probably your id's in html are not the same as requested by javascript ? This "should" work
<div style="display:none" id="toggleText" class="TextFontBold">A:<%#Eval("answer") %></div>
<a id="displayText" href="javascript:toggle();">show answer</a>
精彩评论