I’m writing a class that needs to attach event listeners to objects within a respective sections (#one and #two in this example), but I’m having issues passing variables from the class to set up the jQuery event listeners.
<script type="text/javascript">
function myClass(id) {
this.id = id;
$(document).ready(function(){
$(this.id + ' .filter').click(function(){ alert("You clicked a filter"); });
});
}
one = new myClass('#one');
two = new myClass('#two');
</script>
<div id="one">
<a href="javascript://" class="filter">I am link one</a>
</div>
<div id="two">
<a href="javascript://" class="filter">I am link two</a>
</div>
… unfortunately variable scope doesn’t agree with me; this.id cannot be accessed from within $(document).ready(), and so the event listeners don’t fire. How can I access it?
This is because “this” is a keyword which references the object on which the current function was invoked. With jQuery event handlers, this object is the DOM element on which the event hander was registered (i.e. document in this case.) Use a different variable name to store your object: