我有一系列按钮,我希望根据页面 URL 末尾的散列来单击这些按钮,这些按钮可以根据与页面的交互性而改变。我可以通过按按钮的类 (.fullscreen-button') 以及它们在按钮数组中的编号来选择按钮,但我无法使用它们的唯一 ID 选择相同的按钮。我宁愿通过 ID 选择它们,因为它们在数组中的顺序可以改变。
这是我通过类方法工作的函数...
$(function() {
if ( document.location.href.indexOf('#Programming') > -1 ) {
$('.fullscreen-button')[0].click();
} else if ( document.location.href.indexOf('#3D') > -1 ) {
$('.fullscreen-button')[1].click();
} else if ( document.location.href.indexOf('#Acting') > -1 ) {
$('.fullscreen-button')[2].click();
} else if ( document.location.href.indexOf('#Audio') > -1 ) {
$('.fullscreen-button')[3].click();
}
});
...这就是我尝试的 ID 方法,但它不起作用...
$(function() {
if ( document.location.href.indexOf('#Programming') > -1 ) {
$('#Programming for Web').click();
} else if ( document.location.href.indexOf('#3D') > -1 ) {
$('#3D Design').click();
} else if ( document.location.href.indexOf('#Acting') > -1 ) {
$('#Acting').click();
} else if ( document.location.href.indexOf('#Audio') > -1 ) {
$('#Audio Editing').click();
}
});
为什么在这种情况下不能通过 ID 选择对象?
编辑: 好吧,就是那些该死的空间。感谢大家的帮助!
最佳答案
您不应该在 ID 字符串中使用空格。 http://www.w3.org/TR/html4/types.html
但是,如果这样做,则需要转义 jquery 中的空格以选择它。否则$("#Programming for web")
会寻找 <web>
在:
<div id="Programming">
<for>
<web/>
</for>
</div>
要选择[此无效] ID 字符串,您将使用:$("#Programming\\ for\\ web")
关于jquery - 不能按 ID 选择对象,只能用 jQuery 按类选择对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555912/