jQuery选择框.val('')行为从1.9到1.10+不同,最简单的方法是什么 [英] jQuery select box .val('') behavior differs from 1.9 to 1.10+ what is the shortest way to do that

查看:91
本文介绍了jQuery选择框.val('')行为从1.9到1.10+不同,最简单的方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下jQuery 1.9和1.10 +之间的行为有所不同:

The following behaves differently between jQuery 1.9 and 1.10+:

<select id="s1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

$('#s1 option[value=1]').hide();
$('#s1').val('');

此代码背后的想法是选择第一个选项。

The idea behind this code is to select the first option.

在1.10之后, $('#s1')。val(''); 部分不再以相同的方式工作。我认为它从来没有意味着以这种方式使用,但它的旧代码必须以某种方式进行现代化...

After 1.10, the $('#s1').val(''); part is no longer working in the same way. I suppose that it was never meant to be used that way but its old code and have to be modernized in some way...

在jQuery 1.10之后没有选择任何内容并且 $('#s1')。val()返回 null

After jQuery 1.10 nothing is selected and $('#s1').val() returns null.

将代码更改为:

$('#s1 option[value=1]').hide();
$('#s1').val($('#s1 option').first().val());

同时使用新旧jQuery版本。

Does the job with both new and old jQuery versions.

我的问题是,是否有更短/更优雅的方式来做同样的事情?

My question is if there is shorter/more elegant way to do the same thing?

推荐答案

$("#s1")[0].selectedIndex = 0;

如果你真的喜欢jQuery,你也可以这样做:

You can also do this if you really like jQuery:

$("#s1").prop("selectedIndex", 0);

更多信息: https://stackoverflow.com/a/1314266/283863

这篇关于jQuery选择框.val('')行为从1.9到1.10+不同,最简单的方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆