1

I'm having difficulty understanding how to use event.data to return the value of whatever element the event fired one. Here my example:

<a href="#" class="dw_add">
  <img src="http://something" />
</a>

var callback = function(event){ console.log(event.data.src) }

$('.dw_add')
  .on('click', { src: $(this).find('img').attr('src') },callback);

$this is currently referencing the document and not the that was clicked. Hopefully you can see what I'm trying to do, but my javascript knowledge is limited, think I'm approaching it in a PHP mindset.

Any ideas how to pass the value of 'img src' to the callback?

3 Answers 3

3

You are not inside a functions scope, so this:

$('.dw_add').on('click', { src: $(this).find('img').attr('src') },callback);

will not work as $(this) is not the element you think it is because there is no local scope for the clicked element, no event.target or event.data etc!

However this will work as it has a direct reference to the element and scope for "this" is not an issue:

var callback = function(event){ console.log(event.data.src) }
var elm = $('.dw_add');
elm.on('click', { src: elm.find('img').attr('src') },callback);

and this will work as $(this) is inside a function scope:

function callback(a){ console.log(a) }

$('.dw_add').on('click', function() {
  var a = $(this).find('img').attr('src');
  callback(a);
});​

Also, using $(this) inside the callback function will work, as it is, again, inside a functions scope and has a reference to the targeted element.

Sign up to request clarification or add additional context in comments.

Comments

1

Why not do something like this:

var callback = function(event){ console.log($(this).find('img').attr('src')) }

$('.dw_add')
    .on('click', callback);

Comments

0

In jQuery event handlers, this is set to the DOM element that fired the event. Since you're attaching an event handler to the <a> element, this will be the link.

If you want to get the src of the img, you'll have to find the img element in the triggering a by using find() or children():

$('.dw_add').on('click', function(e) {
    $(this).children('img').attr('src');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.