我有一个元素列表,当通过 url 重定向焦点元素时我需要。
<div id="20"></div>
<div id="21"></div>
<div id="22"></div>
// url
http://localhost:8080/#21
var current_url = window.location.href;
// Capture the string after #
var id = current_url.substr(current_url.indexOf("#") + 1);
$('#'+ id).css('border', '1px solid rgb(204, 255, 248)');
使用前面的代码 jQuery 选择 id 为 21 的元素;
但是当它没有 url 时 # 显示下一个错误:
Uncaught Error: Syntax error, unrecognized expression: #http://localhost:8000/admin/dashboard
我该如何解决?谢谢
最佳答案
改用location.hash
。
var id = location.hash;
if (id)
{
$(id).css('border', '1px solid rgb(204, 255, 248)')
}
出现错误的原因是,如果没有包含 jquery 无法识别的特殊字符的散列,它会返回整个 url
或
在继续之前检查散列
if (location.href.indexOf("#") != 1)
{
// stuff
}
希望对你有帮助
关于html - 通过 url jQuery 重定向时的焦点元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45929771/