Change onclick event with JavaScript not working

时光怂恿深爱的人放手 提交于 2019-12-10 16:49:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!