开发者

Help with jQuery Plugin Development

开发者 https://www.devze.com 2023-02-27 17:04 出处:网络
I was reading a couple of tutorials.This is the link to one of them: http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html

I was reading a couple of tutorials. This is the link to one of them: http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html

In it, the author says,

You'll notice开发者_StackOverflow that whenever I needed to select an element within the plugin, I always used obj as my context (e.g., moreLink = $('.truncate_more_link', obj)). This is necessary to constrain any selections to the current truncated element. Without setting the context like this, you will get unpredictable results.

I've read similar statements in other tutorials, but I still don't grasp what they really mean. In my mind, I understand ...

$('.truncate_more_link', obj)

... to mean, "Select elements with the .truncate_more_link class and also the element represented by the variable obj."

But it sounds like the author of the tutorial is saying "Select the .truncate_more_link class elements that are also the actual element passed into the plugin function. Why not just do

$(obj)

instead of

$('.truncate_more_link', obj)  

It seems I'm missing some understanding of scope.


When you pass two arguments to jQuery, the second argument is used as the "context" for the first. Short version: $('foo', bar) means exactly the same thing as $(bar).find('foo').

Selector Context

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:

$('div.foo').click(function() {
  $('span', this).addClass('bar');
});

When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

http://api.jquery.com/jQuery/#jQuery1

0

精彩评论

暂无评论...
验证码 换一张
取 消