如何在JavaScript中使用onclick [英] How to use onclick in JavaScript

查看:124
本文介绍了如何在JavaScript中使用onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何使用 onclick ,以便它可以重复使用 onclick code> div 一遍又一遍,无需添加无限量的数据。

我不想这样做:

 < 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 区分大小写。所以它是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆