Test Test
Test Test

Reputation: 2899

Strange Javascript behaviour

I am using JQuery to append images, like this:

$('#event_list_main').append('<img class="listed_event" id="event_'+event_counter+'" data-count="'+event_counter+'" src="final_tutorial_buttons/event.png" height="50" width="50" onclick="highlight();" />');

I am assign a highlight function to each image I create and append! The problem is that the highlight function does not execute.

//Highlight function
function highlight()
{
    var indicator = $(this).data("count");
    alert(indicator);

}

the "this" part doesnt seem to work.I want this to refer to each event created.

for example if I created 3 events

event_1 event_2 event_3

and I click on "image event_2" then "this" must refer to "image-event_2"

Upvotes: -1

Views: 70

Answers (2)

Aidiakapi
Aidiakapi

Reputation: 6249

That's not unexpected behavior, you're not passing the this value. But you expect it because jQuery does that automatically for you.

This is an easy fix:

$('#event_list_main').append('<img class="listed_event" id="event_'+event_counter+'" data-count="'+event_counter+'" src="final_tutorial_buttons/event.png" height="50" width="50" onclick="highlight.call(this);" />');

Even though it'd be better to replace it all together with:

$('<img class="listed_event" id="event_' +
     event_counter + '" data-count="' +
     event_counter + '" src="final_tutorial_buttons/event.png" height="50" width="50" />')
     .click(highlight).appendTo("#event_list_main");

Please see this post for more information about how call(), apply() and this.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318798

Try onclick="highlight.call(this);"

However, it would be much cleaner to properly attach an event handler:

var img = $('<img class="listed_event" id="event_'+event_counter+'" data-count="'+event_counter+'" src="final_tutorial_buttons/event.png" height="50" width="50" />');
img.on('click', highlight);
$('#event_list_main').append(img);

Or even more readable:

var img = $('<img/>', {
    'class': 'listed_event',
    id: 'event_' + event_counter,
    src: 'final_tutorial_buttons/event.png'
}).height(50).width(50).data('count', event_counter).on('click', highlight);
$('#event_list_main').append(img);

Upvotes: 4

Related Questions