Most correct way to select option in <select> box

后端 未结 3 618
旧时难觅i
旧时难觅i 2021-01-21 05:13

I know there are multiple ways to select a particular option from a using jQuery:

  1. $select.val(\"someValue\")
  2. $option.attr(\"selected\"
3条回答
  •  花落未央
    2021-01-21 05:56

    The most used way is $select.val("someValue"), this is the official method in the documentation for setting a value of any input, so it'll be the most optimized one as well as they hit performance areas.

    For #2, yes it satisfies this, for #3...it's short and still makes your intent very explicit.

    That being said, the fastest way, if you're setting thousands of select elements is the $select[0].selectedIndex = 1 route...you can't get faster than native DOM properties. When setting the value of one though (unless it has lots of items, in which case again go with .selectedIndex) the speed should be so far it doesn't matter between any of the three.

提交回复
热议问题