【问题标题】:Javascript - Calling a function for an onClick eventJavascript - 为 onClick 事件调用函数
【发布时间】:2014-10-15 03:07:45
【问题描述】:

考虑以下代码:

<html>

<head>
</head>

<body>
    <script>
        function showAlert (text) {
            alert(text);
        }

        x = document.getElementById('aTag');
        x.setAttribute('onclick', "alert('Hello World')"); //WORKS
        x.setAttribute('onclick', "showAlert('Hello World')"); //DNW (showAlert is not defined)
    </script>

    <table>
        <tr>
            <td><a href="javascript:void(0)" id="aTag">TEST</a></td>
        </tr>
    </table>
</body>

</html>

第一个 onclick 分配有效并生成一个超链接,当您单击它时,会打开一个带有Hello World 消息的对话框。可能是因为window.alert方法是global(不知道是不是用对了)。

但是第二个赋值只在点击时返回如下错误:

showAlert is not defined

作为 JS 的初学者,我认为问题可能与 showAlert 函数范围有关,或者可能与 showAlert 函数不存在的 elementNode.setAttribute 方法上下文有关。

我提前感谢大家的时间。

问候。

【问题讨论】:

标签: javascript function onclick


【解决方案1】:

像这样附加它应该可以完成工作:

x.onclick = function() {showAlert("foo");};

Demo

【讨论】:

  • 为什么我不应该在 Firefox 中使用传统的事件处理(第二行)?
  • @FelixKling 不。只是我比较仓促。已更新。
  • 确实,您的语法很短,并且可以完美地完成工作。谢谢!
【解决方案2】:

首先,感谢您花时间回复。

最后,我看了下面的答案:https://stackoverflow.com/a/21477793/3186538,我最终得到了这段代码:

<html>

<head>
</head>

<body>
    <script>
        // Display text function
        function showAlert(text) {
            alert("Called in showAlert: " + text);
        }
        // But for the previous function to work, we must make sure that it is loaded after the rest of the DOM
        window.onload = function() {
            document.getElementById("aTag").onclick = function fun() {
                showAlert("Hello World");
            }
        }
    </script>

    <table>
        <tr>
            <td><a href="javascript:void(0)" id="aTag">TEST</a></td>
        </tr>
    </table>
</body>

</html>

现在,当我单击超链接时,确实会看到一个显示Hello World 消息的对话框。

再次感谢大家(当然还有 SO)。

【讨论】:

    【解决方案3】:

    在您尝试获取该元素时,它还不存在。
    将脚本标签移动到底部,就在结束正文标签之前。

    <table>
        <tr>
            <td><a href="javascript:void(0)" id="aTag">TEST</a></td>
        </tr>
    </table>
    <script>
        function showAlert (text) {
            alert(text);
        }
    
        x = document.getElementById('aTag');
        x.setAttribute('onclick', "alert('Hello World')"); //WORKS
        x.setAttribute('onclick', "showAlert('Hello World')"); //DNW (showAlert is not defined)
    </script>
    

    FIDDLE

    您无法使用尚未输出到 DOM 的 javascript 获取元素,因此无论何时尝试获取元素,请确保它可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 2018-08-13
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      相关资源
      最近更新 更多