val() 方法
.val() 方法主要用于获取input、select、textarea等表单元素的值。
如果在空集上调用它,它将返回 undefined。
当集合中的第一个元素是多选时,val() 返回一个数组,其中包含每个选定选项的值。
如果没有选择任何选项,它将为 jQuery 3.0 版本返回一个空数组。
对于 jQuery 3.0 以下的版本,它返回 null。
prop()
jQuery prop() 方法可以获取 jQuery 1.6+ 版本的所选选项的文本值:
<!DOCTYPE html> <html> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script> <body> <select> <option value="0">Value1</option> <option value="1">Value2</option> </select> <script> let text = 'Value2'; $("select option").filter(function() { //Jan want to use $.trim in here return $(this).text() == text; }).prop('selected', true); </script> </body> </html>
attr() 方法
.attr() 方法仅用于获取匹配集中第一个元素的属性值。
使用 .each() 或者 .map() 循环方法分别获取每个元素的值。
.attr() 方法为那些尚未为 jQuery 1.6 版本设置的属性返回 undefined。
使用 .prop() 方法检索和更改 DOM 属性,例如表单元素的选中、选中或者禁用状态。
attr()
此方法设置所选元素的属性和值。
将其用于 1.6 以下且大于或者等于 1.4 的 jQuery 版本:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> </head> <body> <select> <option value="0">Value1</option> <option value="1">Value2</option> </select> <script> let text = 'Value2'; $("select option").filter(function() { //Jan want to use $.trim in here return $(this).text() == text; }).attr('selected', true); </script> </body> </html>
这种方法适用于 1.6 以上但低于 1.9 的版本。
在 jQuery 1.9+ 版本中它不起作用。
对于 1.9+ 版本,使用 prop() 而不是 attr()。
如果我们有一个 select 元素并希望通过其文本描述设置下拉列表的选定值,我们可以使用不同的 jQuery 方法来实现它。
让我们分别讨论它们,并为我们选择最好的一个。
prop() 方法
.prop() 方法仅用于检索匹配集中第一个元素的属性值。
如果一个属性的值没有被设置或者匹配的集合没有元素,它将返回 undefined。
使用 jQuery 的 .each() 或者 .map() 循环方法分别获取每个元素的值。
val()
val() 方法还设置与传递值对应的选项:
<!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script> </head> <body> <select> <option value="0">Value1</option> <option value="1">Value2</option> </select> <script> let text = 'Value2'; $("select option").filter(function() { //Jan want to use $.trim in here return $(this).text() == text; }).attr('selected', true); </script> </body> </html>