Reputation: 1081
How can i pass the this
with other parameters to function? Tried the following without success:
function update_alt($this,my_param){
this_alt=$(this).attr('alt');
$(this).attr('alt',this_alt+my_param);
}
// $('.asd img').each(update_alt); // passing $this ok
$('.asd img').each(update_alt(this,prompt('alt?',''))); // null
Upvotes: 0
Views: 81
Reputation: 5124
I'd reference your img variable as item
or element
because this
is special keyword and it can be hard to track exactly what is being referred to when moving between functions.
With that in mind, these changes may solve your bug:
function update_alt(item, my_param) {
var $item = $(item);
var new_alt = $item.attr('alt') + my_param;
$item.attr('alt', new_alt);
}
$('.asd img').each(function(index, item) {
update_alt(item, prompt('alt?',''));
});
Upvotes: 1
Reputation: 10698
In update_alt()
, you might rename all your this
to element
, for code clarity. Plus, you weren't using $this
in your function.
Change it for this :
function update_alt(element,my_param){
element_alt= $(element).attr('alt');
$(element).attr('alt',element_alt+my_param);
}
Then, to use it, you should call it in another function, so this
is referring to the current element:
$('.asd img').each(function(){
update_alt(this,prompt('alt?','')); //"this" has a meaning in this closure
});
Upvotes: 1