开发者

JQuery - Collection Iteration

I am new to JQuery. I have a select html element. I am trying to understand how to iterate through the options in the select element. I know how to do it with traditional javascript as shown here:

for (i=0; i<mySelect.options.length; i++)
  alert(mySelect.options[i].value);

However, I'm trying to lear开发者_运维百科n about JQuery more. Can someone show me the best way to iterate through a collection using JQuery?

Thank you


Depends on what you want to do.

  • If you just want to iterative over the collection you could use each.

  • If you want to iterate over the collection and apply a transform to each element (and get a new collection back) there is map.

  • If you just want to select a subset of your collection there is grep.


First off: IMHO it's great that you learn the non-jQuery way. Watch out that you don't slip into the thinking that everything better using jQuery.

To the problem: If you have a DOM reference mySelect to the select then you can get a jQuery object of the options with $(mySelect).find("option"). The usual way to loop through them would be with jQuery's each method and an (anonymous) function:

$(mySelect).find("option").each(function() {
   alert(this.value);
})


Try this:

$("#mySelect options").each(
    alert($(this).attr("value"));
)


i believe you can use the each function for this. See here


This snippet will get all input elements, and for each of them, print its index in the collection of elements (index) and its value to the log.

$(":input").each( function(index) { console.log(index + " " + this.value);})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜