简体   繁体   中英

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. I am relatively new to the 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.

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'); however I keep retrieving the id of the following DIV (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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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