【发布时间】: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