简体   繁体   English

jQuery将重点放在选择列表的所选项目上

[英]jQuery set focus on selected item of a select list

I have a select list that is size="10" - so it always shows 10 of the 100 options available. 我有一个size="10"的选择列表-因此它始终显示100个可用选项中的10个。

When the page loads, the 1st 10 options are always displayed, even if option value 50 is selected . 页面加载时,总是显示第一次10个选项,即使期权价值50 selected

I have read that adding focus to the selected item of the select list will work so that when the page loads option 50 will be displayed in the select list, instead of the 1st 10 options. 我已经读过,将focus添加到选择列表的所选项目将起作用,这样,当页面加载时,选项50将显示在选择列表中,而不是前10个选项中。

However, after reading many threads and searching google, I am unable to work out how to set the focus to the selected item. 但是,在阅读了许多主题并搜索了google之后,我无法找出如何将focus设置到所选项目上。

I am wanting to set both the selected and the focus applied to the item of the select list. 我想无论是设置selectedfocus应用于选择列表中的项目。

Here is what I have tried and does not work: 这是我尝试过但无法使用的方法:

$('#id_preview_style_select option:selected').prop('selected', true);  //set the selected value.

$('#id_preview_style_select option:selected').prop('focus', true);  //does not work.
$('#id_preview_style_select option:selected').focus();  //does not work

This is what I am seeking to achieve: 这是我要实现的目标:

<select id="id_preview_style_select" size="10" autofocus>
  <option value="0">Style 0</option>
  <option value="1">Style 1</option>
  <option value="2">Style 2</option>
  <option value="3">Style 3</option>
  ....
  <option value="50" selected focus>Style 50</option>
  ....
  <option value="99">Style 99</option>
  <option value="100">Style 100</option>
</select>

Any assistance would be appreciated. 任何援助将不胜感激。

.prop('focus', true); would never work since focus() is a method, not a property (need to be invoked). 因为focus()是方法而不是属性(需要被调用),所以它将永远无法工作。

Try $('#id_preview_style_select option:selected').focus(); 尝试$('#id_preview_style_select option:selected').focus();

If it doesn't work right away you might need to timeout it with a timeout of 0 milliseconds. 如果不马上工作,你可能需要timeout以0毫秒为单位的。 Hopefully that will help. 希望这会有所帮助。

Edit: if none of this works (it might be that browsers would not allow this) I'd just scroll the list of options, so user can see what is selected. 编辑:如果这些都不起作用(可能是浏览器不允许这样做),我只是滚动选项列表,以便用户可以看到选择的内容。

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

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