[英]When trying to remove any selected option in an select element, Safari shows it as blank
Examine this code. 检查此代码。 I'm using jQuery, but I think it is probably irrelevant. 我正在使用jQuery,但我认为这可能无关紧要。
$(function() {
$('button').click(function() {
$('select option[selected]').removeAttr('selected');
});
});
<select>
<option>a</option>
<option selected="selected">b</option>
<option>c</option>
</select>
<button>give me a click</button>
This was working fine for having the button reset the select to the first option. 使按钮将选择重置为第一个选项,效果很好。 I just tested it in Safari, and it blanks the select instead of selecting the first. 我刚刚在Safari中对其进行了测试,它使选择内容空白而不是选择第一个。
This isn't an issue, until I got it up and running on an iPad, which is where the majority of this web app will be used. 在我将其安装并在iPad上运行之前,这不是问题,这将是该Web应用程序的大部分使用位置。 The problem with the iPad is, after then selecting an option, the select refuses to display the option selected. iPad的问题在于,然后选择一个选项之后,select拒绝显示所选的选项。 It still displays as blank. 它仍然显示为空白。
What is the best way to get around this? 解决此问题的最佳方法是什么?
You can fix the behaviour by explicitly setting the index using JavaScript's native selectedIndex
property . 您可以通过使用JavaScript的本机selectedIndex
属性显式设置索引来解决此问题 。
$(function() {
$('button').click(function() {
$('select option[selected]').removeAttr('selected');
$('select')[0].selectedIndex = 0;
});
});
If you have more than one select
element, you will need to iterate through with jQuery's each
and set the property on this
. 如果您有多个select
元素,则需要遍历jQuery的each
并在this
上设置属性。
关于什么:
$('select option:first-child').attr('selected', 'selected');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.