选项:选择了不起作用的jQuery 1.9 [英] option:selected not working jquery 1.9

查看:66
本文介绍了选项:选择了不起作用的jQuery 1.9的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容:

  $("select option:contains(fish)").attr('selected', true);

在jQuery 1.9以下的任何版本中都能很好地工作,但是在jQuery 1.9+中根本不起作用.我一直在寻找有关任何更改的任何文档,但没有找到任何内容.

有什么想法如何使此代码与新的jquery一起使用?

示例(默认为jQuery 1.4): http://jsfiddle.net/reigel/TZmEw/

解决方案

对于jQuery 1.9,使用Prop api而不是attr.

$("select option:contains(fish)").prop('selected', 'selected');

OR

 $("select option:contains(fish)").prop('selected', true);

原因:jQuery 1.6引入了.prop()方法来设置或获取节点上的属性,并且不建议使用.attr()来设置属性.但是,在特定情况下,最高1.9版本仍支持使用.attr().当使用选择器来区分属性和属性时,以向后兼容的名义出现的这种行为会引起混乱.

来源: http://jquery.com/upgrade- guide/1.9/#changes-of-note-in-jquery-1-9

在Attr Api中提及:从jQuery 1.6开始,.attr()方法针对未设置的属性返回undefined.此外,.attr()不应在普通对象,数组,窗口或文档上使用.要检索和更改DOM属性,请使用.prop()方法.

来源: http://api.jquery.com/attr/#entry-longdesc

The following:

  $("select option:contains(fish)").attr('selected', true);

Works wonderfully in anything below jQuery 1.9, but does not work at all in jQuery 1.9+. I have been searching for any documentation on any change, but have not found anything.

Any idea how to get this code to work with the new jquery?

Example Here (defaults to jQuery 1.4): http://jsfiddle.net/reigel/TZmEw/

解决方案

Use Prop api instead of attr for jquery 1.9.

$("select option:contains(fish)").prop('selected', 'selected');

OR

 $("select option:contains(fish)").prop('selected', true);

Reason : jQuery 1.6 introduced the .prop() method for setting or getting properties on nodes and deprecated the use of .attr() to set properties. However, versions up to 1.9 continued to support using .attr() for specific situations. This behavior in the name of backwards compatibility causes confusion when selectors are used that distinguish between attributes and properties.

Source : http://jquery.com/upgrade-guide/1.9/#changes-of-note-in-jquery-1-9

Mentioned in Attr Api : As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Source : http://api.jquery.com/attr/#entry-longdesc

这篇关于选项:选择了不起作用的jQuery 1.9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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