Reputation: 1312
function dosomething(){
alert($(this).attr('id')+' called with '+$(this).innerHTML);
}
$('#myElement').click(dosomething);
here is the HTML:
<div id="myElement">click me</div>
Clicking the element works. But the following call from another location does not:
dosomething($('#myElement'));
Working with objects in Javascript is still frustrating to me. Can anyone explain WHY #2 doesn't work, and an elegant way to handle both cases? here is a jsfiddle for reference:
Upvotes: 0
Views: 138
Reputation: 5362
Your function dosomething()
does not accept any arguments. Therefor it will not work. You can choose to use $('#myElemenet').trigger('click');
, or choose to have your function accept an argument which sets the element:
function dosomething(el) {
el = (el) ? el : $(this);
alert(el.attr('id')+' called with '+el.innerHTML);
}
// My suggestion won't work.
// Use dosomething.call(el) instead.
Upvotes: 3
Reputation: 14469
dosomething($('#myElement'));
This doesn't work because the function dosomething()
is not expecting the element to be taken in as the first parameter, and passing it as a parameter does not automatically set it as this
.
The way you should call that method depends on your intended behavior. If what you want is to just call that dosomething
function on that element, then you can do this:
dosomething.call($('#myElement')[0]);
But if your objective is to simulate a click on that element, which would trigger any other click event listeners that may be on that element, then you should do this:
$('#myElement').click();
// or, as @Karl-AndréGagnon pointed out, $('#myElement').trigger('click');
The difference may seem small, but knowing what you really want to happen will probably save you from some headaches down the road.
Upvotes: 2
Reputation: 12305
Try this:
var domething;
$(document).ready(function(){
dosomething = function(elem){
alert(elem.attr('id')+' called with '+elem.attr('title'));
}
$('#myElement').click(function(){
dosomething($(this));
});
});
Upvotes: 0
Reputation: 2634
This is because the this
value of your function was not set. You pass an argument to your function, but expect the this
value to be the argument.
You should instead call that like this:
dosomething.call($("#myelement")[0]);
This will call the function with the this
value of the #myelement
. The [0]
is there because you want the native DOM element, not a jQuery array-like object. This is why you wrap the this
in $(this)
in your function.
Upvotes: 1