using jQuery .each() method on single-element id-selector
Explaining jQuery dialogs in the Nemikor Blog, Scott González uses the .each() method on an id selector:
$('#page-help').each(function() {
var dialog = $('<div></div>')
.load($(this).attr('href'))
.dialog( ... );
$(this).click(function() { ... });
});
Since an id selector can only return a single element, what is the purpose of using the .each() method? (which is normally for i开发者_运维知识库terating over matched elements).
Is it just that there is no simpler way to execute a function for the 'page-help' element which provides access to $(this)?
It lets you mess with something without polluting the surrounding namespace. An alternative might be:
(function($this) {
var dialog = $('<div></div>')
.load($this.attr('href'))
.dialog(...);
$this.click(function() { ... });
})($('#page-help'));
I don't know which of the two is more disturbing. And I suppose I don't really know that that was the reason for doing it that way (that is, namespace tidiness).
He's using a .each()
so this
refers to the element and his variables are encapsulated in that callback function, though this would also work (but you'd have the variables left around):
var $this = $('#page-help'),
dialog = $('<div></div>')
.load($this.attr('href'))
.dialog( ... );
$this.click(function() { ... });
I'd say it's a style choice. I actually like the selector way you show here because it attaches a scope to the primary participant in the logic in a (to me) self documenting way.
It could also be done like this, but that wrapper gives you the fortunate use of $(this) instead of the following code:
var idPageHelp = $( $('#page-help')[0] );
var dialog = $('<div></div>')
.load( idPageHelp.attr('href'))
.dialog( ... );
idPageHelp.click(function() { ... });
Note I'm making an assumption that you want to focus on just the 0th element and I'm also focusing that you want to use idPageHelp as a jQuery object so I'm forcing it to be wrapped in a jQuery object.
Why not just assign a variable?
var ph = $('#page-help')
var dialog = $('<div></div>')
ph.load($(this).attr('href'))
ph.dialog( ... );
$(ph).click(function() { ... });
});
精彩评论