如何在JavaScript中使用onclick [英] How to use onclick in JavaScript
问题描述
我需要知道如何使用 onclick
,以便它可以重复使用
我不想这样做:
< div id =div1onClick =divFunction1()>
< / div>
< div id =div2onClick =divFunction2()>
< / div>
< div id =div3onClick =divFunction3()>
< / div>
< div id =div4onClick =divFunction4()>
< / div>
但是,如果可能,请在JavaScript中执行此类操作:
div = document.getElementById(allPurposeDiv)。onclick ...
我并不确定在onclick之后会出现什么问题。
任何帮助都是appriciated,谢谢!
onclick
。它期望一个回调函数被分配给它,它将被调用。
document.getElementById(div1)。onclick = divFunction;
如果你想添加更多的事件,那么你需要一个像adeneo建议的事件监听器。
I need to know how to use onclick
so that it allows me to reuse the onclick
method of a div
over and over again and not have to add an infinite amount of them.
I don't want to have to do this:
<div id="div1" onClick="divFunction1()">
</div>
<div id="div2" onClick="divFunction2()">
</div>
<div id="div3" onClick="divFunction3()">
</div>
<div id="div4" onClick="divFunction4()">
</div>
But instead do something like this in JavaScript if possible:
div = document.getElementById("allPurposeDiv").onclick...
I'm not exactly sure what would come after onclick is the problem.
Any help is appriciated, Thanks!
onclick
is case sensitive. So it is onclick
. It expects a callback function to be assigned to it, which will be called.
document.getElementById("div1").onclick = divFunction;
If you are trying to add more events, then you need a event listener like what adeneo has suggested.
这篇关于如何在JavaScript中使用onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!