从div调用Javascript函数

3
我可以请您帮忙吗?我想在HTML中引用一个DIV时调用一个JavaScript函数。
这是我的函数:
        function testFunction()
        {
            alert("Test");
        }

我希望在HTML中引用以下内容时调用testFunction函数:
<div id="testFunction"> 

可以帮我做这件事吗?

“when the following reference is made” 究竟是什么意思?是指当解析器遇到具有此ID的元素时吗?JavaScript 要么在解析器在 HTML 中遇到它时执行,要么作为对某些用户交互的反应而执行。那么,“引用”是什么样的交互呢?你的问题并不是很清楚。 - Felix Kling
1个回答

3
您可以将调用附加到单击处理程序中:
在标记中:
<div id="testFunction" onclick="testFunction()"> 

或者在您的脚本块内:

function testFunction() {
   alert("Test");
}

var el = document.getElementById("testFunction");
el.onclick = testFunction;

var el = document.getEl...等等是不必要的,因为已经有onclick属性。 - miru87

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接