i have this html:
<ul id="list1" class="eventlist">
<li>plain</li>
<li class="special">special <button>I am special</button></li>
<li>plain</li>
</ul>
and I have this jquery code:
$('#list1 li.special button').click(function(开发者_如何学编程event) {
var $newLi = $('<li class="special"><button>I am new</button></li>');
var $tgt = $(event.target);
});
My question is what is the difference between
var $tgt = $(event.target);
and
var $tgt = event.target;
event.target
is a reference to the DOM node.
$(event.target)
is a jQuery object that wraps the DOM node, which lets you use jQuery's magic to query manipulate the DOM.
In other words, you can do this:
$(event.target).addClass('myClass');
but you can't do this:
event.tagert.addClass('myClass');
In the first case, the local varialbe $tgt
will hold the jQuery element (wrapped around a DOM element), in the second case it will hold the DOM element.
You cannot use the jQuery manipulation methods (such as .val()
) directly on DOM elements, hence you need to convert it to a jQuery element first if you want to do so.
I'd advise just using $(this)
to grab the element. jQuery does that internally so you don't have to:
$('#list1 li.special button').click(function() {
var $tgt = $(this);
});
To answer your question: $(event.target)
will be extended with jQuery, and event.target
won't.
精彩评论