【发布时间】:2023-03-08 18:57:01
【问题描述】:
我正在尝试使用 jQuery 更改选择下拉框中的选定选项。我对其进行了设置,以便它在 URL 的末尾找到哈希标记,并根据该哈希标记更改选择框中的选定选项。
我的大部分代码都是正常运行的,它成功地找到了哈希标签并执行了与之对应的 if 语句。但是,当它转到选项的选择器(它使用基于选项标签的 value 属性的属性选择器)时执行语句的“then”部分时,它返回 null。如果用萤火虫解决了这个问题,在控制台中它会说选择器为空。
这是我的代码:
$(document).ready(function() {
var $hash = window.location.hash
if($hash == "#htmlcss") {
$('option[value="HTML/CSS Coding"]').attr("selected","selected")
}
if($hash == "#php") {
$('option[value="PHP Coding"]').attr("selected","selected")
}
if($hash == "#jscript") {
$('option[value="Javascript and jQuery Coding"]').attr("selected","selected")
}
if($hash == "#improv") {
$('option[value="General Website Improvements"]').attr("selected","selected")
}
if($hash == "#towp") {
$('option[value="Website Conversion to Wordpress"]').attr("selected","selected")
}
if($hash == "#wptheme") {
$('option[value="Wordpress Theme Design"]').attr("selected","selected")
}
if($hash == "#complete") {
$('option[value="Complete Website Creation"]').attr("selected","selected")
}
if($hash == "#server") {
$('option[value="Web Server Configuration"]').attr("selected","selected")
}
});
所以澄清一下,例如,当我输入一个以 #php 哈希标记结尾的 url 时,不会发生所需的操作,这会通过使用“selected”将“PHP Coding”选项更改为选定的选项html 属性,但是特定选项标签的选择器返回 null。我的语法有问题还是我的代码没有按照我认为应该的方式运行?非常感谢。
【问题讨论】:
-
您确定这些是值,而不是
<option>元素的文本文本吗?另外,<select>的名称是什么,有一个更简单的方法:)
标签: javascript jquery html forms jquery-selectors