Most correct way to select option in <select> box

后端 未结 3 616
旧时难觅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:38

    As Nick Craver mentioned any of these will work, it really depends on the context as to which will be best for your needs.

    Personally, if I need speed I just use something like (not tested, just an example):

    var elem = document.getElementById('myselectid');
    elem.options[1].value = 'some value'
    

    But, you lose the benefits of jquery by doing this.

    If you need to do many changes, based on a pattern, for example, then you can use jquery to help with that, which will reduce the amount of untested code you need to write. For a nice list of patterns you can do you can look at this: http://www.myphpetc.com/2009/03/jquery-select-elements-tips-and-tricks.html.

    So, there is no one best approach that is best in any situation, which is why there are so many ways to set an option in a select element, but, if you give a user story where you are doing this, then a specific best practice can be explained.

提交回复
热议问题