JavaEar 专注于收集分享传播有价值的技术资料

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"

4个回答

    最佳答案
  1. you must make sure your updated code had been deployed.

    you can check the html source .

    and your posted code has no any problem.

  2. 参考答案2
  3. 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.

  4. 参考答案3
  5. 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)?

  6. 参考答案4
  7. First, simplify the problem, see if the following function works.

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