$('select option:selected').text()和Attr.指定的已弃用警告

$('select option:selected').text() and Attr.specified is deprecated warning

本文关键字:警告 option select selected text Attr      更新时间:2023-09-26

在我的项目中,我需要用<select>的选定值和文本更新主干模型。

为了这个目的我打电话给

model.set 'value', $('select').val()
model.set 'value_text', $('select option:selected').text()

(我也使用咖啡脚本)。由于jQuery v2.0.3的一些问题,我目前正在使用我收到这个警告:

Attr。指定已弃用。它的值总是true。

我知道在SO上有关于这个警告的问题,但是我想问一些完全不同的问题:

由于更新到较新版本的jQuery(问题可能会被修复)是不可能在接下来的几个月,我想问是否有其他的方式来接收所选选项的文本,而不是上面使用的。我不反对纯JS解决方案,如果没有其他使用jQuery。

任何帮助都非常感谢。

EDIT for @KevinB:该警告是由询问该选项上是否有selected属性引起的。

要在不更改任何其他内容的情况下*修复*它,只需使用。filter.

$('select option').filter(function (i) { return this.selected; }).text();

我更喜欢用另一种方法。查看代码

里面的观点。

events:
    "change input":"updateModel"
    "change select" : "SelectedItem" //Just for example.
selectedItem:(element)->
    selectedOption = element.target.selectedOptions
    alert **selectedOption.item().value** // the value of the selected item. now you can set it on model.
updateModel:(element)->
    @model.setNew(element.target.name, element.target.value)

内部模型。

setNew:(newName, newValue)->
    @set newName, newValue

Html文件。

<select>
<option value="renan">Renan</option>
<option value="carvalho">Carvalho</option>
</select>
<input type="text" name="customer" />

希望能有所帮助。