Javascript“onClick”事件不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7239848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:26:56  来源:igfitidea点击:

Javascript "onClick" event doesn't work

javascriptjavascript-events

提问by itamar

I have this line in my php file:

我的 php 文件中有这一行:

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:

该函数位于外部 JS 文件中。这是函数声明:

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

页面中的其他“onclick”事件和 JS 函数正在工作。

    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"

控制台显示“ReferenceError: showOld 未定义”

回答by shenhengbin

you must make sure your updated code had been deployed.

您必须确保已部署更新的代码。

you can check the html source .

你可以检查html源。

and your posted code has no any problem.

并且您发布的代码没有任何问题。

回答by Cristian Necula

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

尝试打开 firebug 的控制台(或 chrome 开发工具)并检查是否有任何脚本错误。

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:

您应该避免编写内联 javascript。这使得调试和维护代码库变得更加困难。我建议您阅读以下有关 javascript 事件的文章:

Quirksmode - Early Event Handlers

Quirksmode - 早期事件处理程序

Quirksmode - Traditional event registration model

Quirksmode - 传统的事件注册模型

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.

尽管内联事件注册模型古老且可靠,但它有一个严重的缺点。它要求您在不属于它的 XHTML 结构层中编写 JavaScript 行为代码。

回答by Andrew D.

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)?

javascript 控制台中究竟显示了什么(如果可用)?

回答by Rufus

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

先把问题简化一下,看下面的函数是否有效。

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