I am working on a site that displays multiple entries. Each entry can be expanded/collapsed, showing more/less information. The HTML for each entry looks like:
<div id="entry-1"><div>some text</div><div><img></div></div>
<div id="entry-2"><div>some text</div><div><img></div></div>
<div id="entry-3"><div>some text</div><div><img></div></div>
The 1,2,3 in “entry-{1,2,3}” is the id of each post. How do I tie a click event to each div?
I tried doing:
$('div[id^="entry-"]').click( myFunc($(this)) ) ;
But when I click, nothing happens, the click doesn’t fire even though when the page loads, the JavaScript is executed.
The problem is the
thiskeyword. In this code…… the
thisvalue doesn’t point to the DOM element that has been clicked, but instead to the global object (window).This would work:
As @JCOC pointed out, you are calling the function.
In your original code,
myFunc($(this))will be called immediately and its return value is passed into theclick()method.So, if your function returned
undefined, for instance, then the resulting code would be this:… which obviously doesn’t work.