Reputation: 29474
How do you pass something to a function, as if it calls the function?
Say I have this function
function ShowId() {
alert($(this).attr('id'));
}
and this HTML
<div id='div1'>
<a class='link'>Some link</a>
</div>
I want to do this
$('div .link').click(function() {
$(this).parent('div').call(ShowId); // What is the right syntax?
});
and it should alert: div1
Upvotes: 2
Views: 73
Reputation: 8171
You can pass your element as a object in your function-
$('div .link').click(function() {
ShowId($(this).parent('div'));
});
function ShowId(Obj) {
alert(Obj.attr('id'));
}
Upvotes: 0
Reputation: 15603
Use this code:
$('div .link').click(function() {
var parentObj = $(this).parent('div');
ShowId(parentObj); // call the function with arguments simply
});
And your function will be:
function ShowId(that) {
alert($(that).attr('id'));
}
Upvotes: 0
Reputation: 123473
.call()
is a method of function
s, so the order is the other way around:
ShowId.call($(this).parent('div'));
Though, passing as an argument is also usually viable:
function ShowId(elem) {
alert($(elem).attr('id'));
}
ShowId($(this).parent('div'));
Upvotes: 4
Reputation: 29186
Pass the jQuery element:
function ShowId($this) {
alert($this.attr('id'));
}
$('div .link').click(function() {
$(this).parent('div').call(ShowId($(this)));
});
Upvotes: 0