简体   繁体   English

div上的JavaScript click事件

[英]JavaScript click event on div

I am working on JavaScript project and I am having a problem with click event and retrieving the correct information about the element clicked. 我正在处理JavaScript项目,但单击事件有问题,并且正在检索有关单击元素的正确信息。 I am relatively new to the JavaScript. 我对JavaScript比较陌生。

The real code I am working on is fairly complex however I am posting only a chunk of code to illustrate my problem. 我正在使用的实际代码相当复杂,但是我只发布了一部分代码来说明我的问题。

 function App(){ this.name = "New App"; } App.prototype.createDIV = function() { var h = "<div class='clickable' id='idToShow'><div class='name' id='notToShow'>" + this.name + "</div></div>"; $('#content').html(h); } App.prototype.showID = function(e) { if (e.target.id == 'idToShow') { alert(this.name); // this doesn't display, because incorrect ID is retrieved } } $(document).ready(function() { var newApp = new App(); $("input#btn").click(newApp.createDIV.bind(newApp)); $("div").on("click", ".clickable", newApp.showID.bind(newApp)); }); 
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <div id="content"></div> <input type="button" id="btn" value="CLICK"> 

I have a object in the app with number of prototypes. 我的应用程序中有一个带有多个原型的对象。 On document load, object is constructed, events are attached to elements and bind to object. 在文档加载时,将构造对象,将事件附加到元素并绑定到对象。 Clicking the button, new set of div results are created dynamically. 单击该按钮,将动态创建一组新的div结果。

Now this is where it starts to go wrong for me. 现在,这对我来说开始出错了。 I attached an event to div with the class CLICKABLE and I would like to retrieve the id of that particular DIV element (id='idToShow'); 我将一个事件附加到类为CLICKABLE的div上,我想检索该特定DIV元素的id(id ='idToShow'); however I keep retrieving the id of the following DIV (id='notToShow'). 但是,我一直在检索以下DIV的ID(id ='notToShow')。

I might not fully understand why is this happening and what to do to prevent it in order to get the correct ID. 我可能不完全了解为什么会发生这种情况,以及如何采取措施防止这种情况以获取正确的ID。

尝试使用if (e.currentTarget.id == 'idToShow')代替if (e.target.id == 'idToShow')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM