jQuery in Action

246
CHAPTER 8
Talk to the server with Ajax
Let's tackle the
emptySelect()
command first.
$.fn.emptySelect = function() {
return this.each(function(){
if (this.tagName=='SELECT') this.options.length = 0;
});
}
We learned how to add new jQuery commands in chapter 7, and we apply those
techniques here to augment
$.fn
with a new function named
emptySelect
.
Remember that, when such a function is invoked, the function context (
this
) is the
matched set. By applying
each()
to the matched set, we iterate through all the ele-
ments in the set, calling the iterator function specified as the parameter to
each()
.
Within that function, the function context is the individual element for the cur-
rent round of the iteration. We check this element to ensure that it's a
<select>
element, ignoring any other element type, and set the length of the
options
array
for the element to 0. This is a supported, cross-browser way to remove all options
from the dropdown.
Note that we return the wrapped set being operated on as the value of the func-
tion, ensuring that this command can participate in any jQuery command chain.
Easy enough! Now let's tackle the
loadSelect()
command.
We add the following function to the
$.fn
namespace:
$.fn.loadSelect = function(optionsDataArray) {
return this.emptySelect().each(function(){
if (this.tagName=='SELECT') {
var selectElement = this;
$.each(optionsDataArray,function(index,optionData){
var option = new Option(optionData.caption,
optionData.value);
if ($.browser.msie) {
selectElement.add(option);
}
else {
selectElement.add(option,null);
}
});
}
});
}
This command is slightly more involved.
As the lone parameter to this command, we expect a JavaScript construct as
defined in the previous section--an array of objects, each of which possesses a
value
and a
caption
property that define the options to be added to the
<select>
element.


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.