简体   繁体   English

在<select>框中选择选项的最正确方法

[英]Most correct way to select option in <select> box

I know there are multiple ways to select a particular option from a using jQuery: 我知道有多种方法可以从使用jQuery中选择一个特定的选项:

  1. $select.val("someValue")
  2. $option.attr("selected", "selected")
  3. $select[0].selectedIndex = 1

Assuming you have both the index of the option you wish to be selected and its value, what's the most correct way (from the above, or otherwise) to make it selected? 假设您同时拥有要选择的选项的索引及其值,那么选择哪种方法(从上面或其他方面)最正确的方法是什么?

By "most correct", I mean: “最正确”,我的意思是:

  1. Best practice, if any 最佳实践,如果有的话
  2. Will correctly set the value so that it is submitted with the form, and can be retrieved using any of the above methods 将正确设置值以便与表单一起提交,并可以使用上述任何方法检索
  3. Any other reason why I'd choose one method over others 我选择一种方法而不是其他方法的任何其他原因

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. 最常用的方法是$select.val("someValue") ,这是文档中用于设置任何输入值的官方方法,因此它将是最优化的方法以及它们达到性能区域。

For #2, yes it satisfies this, for #3...it's short and still makes your intent very explicit. 对于#2,是的,它满足于此,对于#3 ......它很短并且仍然使你的意图非常明确。

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. 话虽这么说, 最快的方法,如果你设置成千上万的选择元素是$select[0].selectedIndex = 1路由......你不能比原生DOM属性更快。 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. 当设置值为1时(除非它有很多项目,在这种情况下再次使用.selectedIndex ),速度应该是到目前为止,三者之间的任何一个都无关紧要。

$select.val("someValue") $ select.val( “someValue中”)

That's fine, in the common case where it's a non- multiple select and you don't have two different <option> s with the same value . 这很好,在常见的情况下,它是非multiple选择,并且您没有两个具有相同value不同<option> If that's the case I'd go with this, as the most readable option. 如果是这种情况,我会选择这个,作为最可读的选项。

$select[0].selectedIndex = 1 $ select [0] .selectedIndex = 1

That's more direct, so marginally quicker, and is necessary to be unambiguous for the case where you have multiple options with the same value. 这更直接,更快,并且对于具有相同值的多个选项的情况,必须明确无误。

If you might have a multiple -select, you have to get/set the selectedness of each option separately: 如果您可能有multiple选择,则必须分别获取/设置每个选项的选择性:

$select[0].options[1].selected= true;

However: 然而:

$option.attr("selected", "selected") $ option.attr(“已选中”,“已选中”)

Not generally the best approach. 通常不是最好的方法。 The problem with attr() is it's a nasty hack to access DOM properties and HTML attributes as if they are the same thing, trying to hide the difference from you. attr()的问题是访问DOM属性和HTML属性是一个讨厌的黑客,好像它们是同一个东西,试图隐藏与你的区别。 What attr() will do in this case is to set the selected DOM property , which is a boolean value. attr()在这种情况下将做的是设置selected DOM 属性 ,这是一个布尔值。 So attr('selected', true) would make more sense; 所以attr('selected', true)会更有意义; 'selected' as a string value does also work, but only because all non-empty string values are 'truthy' in JavaScript. 'selected'作为字符串值也可以,但只是因为JavaScript中的所有非空字符串值都是'truthy'。

If you were actually setting the HTML selected attribute here, it would not have an effect on the selectedness of the option, because the selected attribute actually maps to the defaultSelected property and not selected ! 如果您实际上在此处设置HTML selected属性,则它不会对选项的选择性产生影响,因为selected 属性实际上映射到defaultSelected属性而未selected The selected property reflects the runtime form contents as altered by the user; selected属性反映用户更改的运行时表单内容; defaultSelected reflects the actual attribute in the document containing the initial selectedness state. defaultSelected反映包含初始选择状态的文档中的实际属性。

(Except on IE, due to a bug in its implementation of default values, and also in other browsers in some situations which are too intricate and confusing to go into. Take-home advice: don't try setting the selected HTML attribute from script as the results may be unpredictable. Work with the DOM properties. The same is also true of value / defaultValue for inputs and checked / defaultChecked for checkbox/radio.) (除了在IE上,由于其默认值的实现存在错误,并且在某些情况下也会在其他浏览器中过于复杂且容易引起混淆。带回家的建议:不要尝试从脚本中设置selected HTML属性因为结果可能是不可预测的。使用DOM属性。对于输入的value / defaultValue也是如此,对于checkbox / radio, checked / defaultChecked也是如此。)

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. 但是,通过这样做,你失去了jquery的好处。

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. 例如,如果您需要根据模式进行许多更改,那么您可以使用jquery来帮助解决这个问题,这将减少您需要编写的未经测试的代码量。 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 . 有关一个很好的模式列表,你可以看看: 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. 因此,没有一种最好的方法在任何情况下都是最好的,这就是为什么有很多方法optionselect元素中设置一个option ,但是,如果你给一个用户故事你在做这个,那么一个特定的最佳方法练习可以解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM