添加类选择的相对URL
Add class selected relative URL
我正在尝试使高亮类选择到我的类别:
这是我的代码:
<div id="category">
<ul>
<a href="category.php?c=electronic">
<li>Electronic</li>
</a>
<a href="category.php?c=fashion">
<li>Fashion</li>
</a>
</ul>
</div>
CSS: .selected {border-bottom:3px solid red; }
脚本:
$("#category ul a").each(function(){
if ($(this).attr("href") == window.location.href){
$(this).addClass("selected");
}
});
当我点击电子类时,它会显示高亮类。选择,但是,当URL页面将更改为category.php?c=electronic&page=2
时,问题出现了。Highlight class .selected不再显示,如何修改这个jQuery,让它再次显示?我发现JavaScript 拆分URL文章,它是否适用于这个问题?
使用。indexof代替。
var url = $(this).attr("href");
var windowURL = window.location.href;
if (windowURL.indexOf(url) != -1){
$(this).addClass("selected");
}
$("#category ul a").each(function() {
var url = $(this).attr("href");
var windowURL = "category.php?c=electronic&page=2";
console.log(windowURL, url, windowURL.indexOf(url)); // <--- see how the values change
if (windowURL.indexOf(url) != -1) {
$(this).addClass("selected");
}
});
.selected {
color: red;
border-bottom: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="category">
<ul>
<a href="category.php?c=electronic">
<li>Electronic</li>
</a>
<a href="category.php?c=fashion">
<li>Fashion</li>
</a>
</ul>
</div>
您可以使用.indexof()函数检查url中字符串是否存在
这里我已经更新了你的代码:
$("#category ul a").each(function(){
if (window.location.href.indexOf($(this).attr("href")) > -1){
$(this).addClass("selected");
}
});
.selected {border-bottom:3px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="category">
<ul>
<a href="category.php?c=electronic">
<li>Electronic</li>
</a>
<a href="category.php?c=fashion">
<li>Fashion</li>
</a>
</ul>
</div>
相关文章:
- 为什么html src属性中的相对url是因为Javascript函数中的完整路径
- 如何在从剃刀视图移动内联JavaScript时保留相对URL
- Backbone.js&Handlebars.js来创建相对URL
- JSF元素在外部上下文中加载了相对url
- 正则表达式,用于匹配字符串开头的协议相对 URL
- 使用来自 iframe 的相对 url 跨域导航 parent.window
- 无法获取相对 URL 在 OpenLayers3 中的工作
- 带有Javascript/Jquery的POSTS的相对URL - 简洁
- 图像中的 wysiHTML5 相对 URL
- 替换 Facebook Feed 中的相对 URL
- 是否可以将相对 URL 提供给 Phantom.js页面生成器以获取 PDF 渲染
- 使用本机输入类型=“date” 的 jQuery UI 的协议相对 URL 方法
- 具有相对url的window.location
- 使用JavaScript为MVC应用程序构建相对URL
- 在文档根服务器上的任何CSS、JS、HTML、PHP和TPL文件上,将http替换为相对url//
- 从绝对url获取相对url
- 如何使用http代理中间件重定向/代理来自browsersync的相对url
- JSP/JavaScript web应用程序中的绝对URL与相对URL
- 在jQuery代码中,您将相对url放在哪里
- openDialog()中是否可以使用相对URL/路径