html - 通过 url jQuery 重定向时的焦点元素

标签 html css

我有一个元素列表,当通过 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/

相关文章:

html - 如何在桌面 View 中左对齐图像并在移动 View 中将其居中?

javascript - Android 4.0.3,window.openDatabase 不工作

php - echo html 页面并从 php 变量将值输入到表单中

html - 英镑符号从 H3 中消失

css - 如何将 Angular 的模拟封装属性应用于动态添加到 Angular 组件的 HTML 元素?

javascript - 选择具有不同类的元素(不是一个元素具有多个类)

javascript - 如何在单击某个按钮时激事件画?

css - 子菜单箭头未在移动设备上显示

css - 如何将另一个div中的div放置到绝对位置?

javascript - Skrollr 不能在 html 和 body 上使用 100% 高度