How to call a jquery function from an <a> tag and pass $(this), so that jquery doesn't have to use a class or id to find the element
I am trying to write efficient jquery functions, so I was wondering if there is开发者_开发知识库 a way to pass the element itself $(this), rather than a class or an id to jquery in order to make changes to it when is interacted with.
<a href="#" onclick="myfunc()" />
<script type="text/javascript">
function myfunc() {
$(this).css( { 'color': '#770' } );
}
</script>
If you've already got a reference to an element, you can pass that to the "$()" function and jQuery will do the right thing (that is, exactly what you're asking for here).
So,
var element = document.getElementById("something");
var $element = $(element);
Now there's a slight difference between the results here, and usually doesn't matter. Specifically, when you use a selector to find elements with jQuery, the resulting jQuery object remembers the selector string. When you wrap jQuery around an element, however, there's no selector string to remember.
I'm pretty sure you can also pass an array of element references to "$()" and (maybe; I'd have to try it) a NodeList.
What do you mean by call a jQuery function from an <a>
tag? Do you mean run the function when it's clicked? If you apply an id to the tag, you can do something like this:
$("a#whateverid").click( function(event) {
// Now you can do stuff with $(this)
});
That registers that function with the click event on that element. You can use whatever selector you want (like "a.someclass" if you have a bunch of links with the same class). You can bind to a bunch of different events.
You might also want to do event.preventDefault()
-- that'll prevent the "normal" behavior of clicking on the element (for <a>
tags, following the link, for <button>
tags, submitting the form, etc).
You do exactly that. Say if you were handling the click event for an <a>
$('#myLink').click(function () {
//change the link color to pink
$(this).css('color', '#fedfed'):
//return false to stop the usual link behavior
return false;
});
All jQuery event handlers are passed the element itself:
$('#aId').click(function(e) {
// $(this) refers to <a> element
});
$('a.someclass').click(function(){//code})
This is actually equivalent to
<a class='someclass' onclick='someFunc()'>Link</a>
It's not the same, but it's equivalent.
The first method is the recommended way to go about this. You can always access the element inside it with $(this)
. There isn't anything inefficient about this.
You could also look into jQuery delegate : http://api.jquery.com/delegate/ This will allow you to bind events to the parent element and let you decide on what element/event combinations to act on. This has the advantage of not having to bind events to multiple functions and elements.
Try this one http://jsfiddle.net/tbHzT/
精彩评论