Note that there are some explanatory texts on larger screens.

plurals
  1. POJS onclick triggers wrong object
    primarykey
    data
    text
    <p>what I'm trying to do here is to associate a DOM object with an instance of a JS object, which will provide some meaningfol methods later on ;) At this point I just want to handle my JS object the click event, whilst keeping it's references intact.</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;script type="text/javascript"&gt; // my object, which will hold a reference to a single DOM object obj = function(domobj) { this.o = domobj; my = this; var ref = my.click; this.o.onclick = ref; } // my objects click function obj.prototype.click = function() { alert(my.o.innerHTML); } // create objects with references $(document).ready(function() { o1 = new obj(document.getElementById('b1')); o2 = new obj(document.getElementById('b2')); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button id="b1"&gt;button 1&lt;/button&gt; &lt;button id="b2"&gt;button 2&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Expected result:</strong> when clicking on button 1, the text "button 1" should be alerted.</p> <p><strong>Current result:</strong> when clicking button 1, the text "button 2" is alerted.</p> <p>What I found out so far is that the wrong instance of obj is triggered from the click event, even though o1 and o2 maintain correct references to their corresponding DOM object.</p> <p>Any ideas how to solve this?</p> <p>Thanks for your help!</p> <p>Best regards, Clemens</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload