问题
I have this:
function tp_visible(action){
if(action==1){
document.getElementById("tp").style.display='block';
document.getElementById("tp_action").onclick='tp_visible(0);
return false;';
}
else {
document.getElementById("tp").style.display='none';
document.getElementById("tp_action").onclick='tp_visible(1);
return false;';
}
return false;
}
Why isn't the above changing the onclick
event?
I use Firebug and the event remains the same...
Here is the HTML:
<a
id='tp_action'
name='tp_action'
href='#'
onclick='tp_visible(1);
return false;'
>Show info</a>
回答1:
The check below will work for you because you cannot assign a string value to the handler onclick
.
function tp_visible(action){
if(action==1){
document.getElementById("tp").style.display='block';
document.getElementById("tp_action").onclick= function ()
{ tp_visible(0); return false;};
}
else {
document.getElementById("tp").style.display='none';
document.getElementById("tp_action").onclick= function ()
{tp_visible(1); return false; }
}
return false;
}
回答2:
If you are starting out with Javascript I suggest you get aquainted with one of the many excellent javascript libraries and never try to write this stuff for yourself again - it leads to loosing your mind.
- YUI
- JQuery
- DoJo
Also you could do worse than to purchase Javascript the Good Bits and watch the set of videos by Douglas Crockford.
来源:https://stackoverflow.com/questions/4244401/change-onclick-event-with-javascript-not-working