简体   繁体   中英

Javascript “onClick” event doesn't work

I have this line in my php file:

echo "<input type='button' id='showButton' value='show'  onclick='showOld()'>";

The button is displayed but when it is clicked, nothing happens.

The function is located in an external JS file. this is function declaration:

Other "onclick" events and JS functions in the page are working.

    function showOld()
    {
    alert("njkh");
    var table = document.getElementById("showExp");
    var button = document.getElementById("showButton");
    if (table.style.display == "none")
    {
        table.style.display = "inline";
        button.value = "הסתר ניסויים ישנים";
    }
    else if (table.style.display == "inline")
    {
        table.style.display = "none";
        button.value = "הצג את כל הניסויים";
    }       
    }

console says "ReferenceError: showOld is not defined"

you must make sure your updated code had been deployed.

you can check the html source .

and your posted code has no any problem.

Try opening up firebug's console (or chrome dev tools) and check for any script errors.

You should avoid writing inline javascript. It makes it harder to debug and maintain your codebase. I recommend that you read the following articles on javascript events:

Quirksmode - Early Event Handlers

Quirksmode - Traditional event registration model

A quote from the article:

Although the inline event registration model is ancient and reliable, it has one serious drawback. It requires you to write JavaScript behavior code in your XHTML structure layer, where it doesn't belong.

Try next to check for exceptions:

<input type='button' id='showButton' value='show' onclick='javascript:alert(1);try{showOld()}catch(e){alert(e)}' />

And what exactly is displayed in the javascript console (if available)?

First, simplify the problem, see if the following function works.

function showOld() {
alert('test');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM