Jquery:动态改变<链接>的取决于路径名链接>
我们想要在链接上添加类,具体取决于window.location.pathname,
我们的html是:
<nav>
<a href="index.php">Home</a>
<a href="company.php">Company</a>
<a href="products.php">Products</a>
<a href="technical.php">Technical</a>
<a href="services.php">Services</a>
<a href="contactus.php">Contact Us</a>
</nav>
并且文档URL是www.nicadpower.com/index.php 因此,
var page_name = window.location.pathname.substring(1);
在获取/知道路径名为 'index.php' 后,我们希望 jquery 能够将 'page_name' 与 进行比较>href 以及如果它等于添加一个 class="current"
使我们的 html 代码像这样
<nav>
<a href="index.php" class="current">Home</a>
<a href="company.php">Company</a>
<a href="products.php">Products</a>
<a href="technical.php">Technical</a>
<a href="services.php">Services</a>
<a href="contactus.php">Contact Us</a>
</nav>
We want to add class on a link depending on window.location.pathname
our html is:
<nav>
<a href="index.php">Home</a>
<a href="company.php">Company</a>
<a href="products.php">Products</a>
<a href="technical.php">Technical</a>
<a href="services.php">Services</a>
<a href="contactus.php">Contact Us</a>
</nav>
and the document URL is www.nicadpower.com/index.php and so we did
var page_name = window.location.pathname.substring(1);
after getting/knowing the pathname to be 'index.php' we want jquery to do it's tricks comparing the 'page_name' to href and if it's equal would add a class="current"
making our html code to be like this
<nav>
<a href="index.php" class="current">Home</a>
<a href="company.php">Company</a>
<a href="products.php">Products</a>
<a href="technical.php">Technical</a>
<a href="services.php">Services</a>
<a href="contactus.php">Contact Us</a>
</nav>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能根本不需要 JavaScript,请参阅最后的示例。
您正在寻找“属性等于选择器”,
或者可能是“属性结尾为” 选择器不,等于选择器有效:“属性等于选择器”是 CSS 2.1 并得到广泛支持,因此您可能根本不需要 JavaScript,只需使用样式表即可做到这一点。结尾选择器是 CSS3 并且可能不受支持,如果您需要支持旧版浏览器,当然不行。
这是一个使用 jQuery 和 CSS 的示例页面。使用“属性等于”选择器的 CSS 版本在 IE7 及更高版本、Firefox、Chrome、Opera 和 Safari 上运行良好。 (CSS 位在 IE6 上不起作用,这令人震惊。)
You may not need JavaScript for this at all, see the example at the end.
You're looking for the "attribute equals selector",
or possibly the "attribute ends with" selectornope, the equals selector works:The "attribute equals selector" is CSS 2.1 and broadly-supported, so you could probably do this without JavaScript at all, just using a stylesheet. The ends-with selector is CSS3 and probably not as well supported, certainly not if you need to support older browsers.
Here's an example page using both jQuery and CSS. The CSS version using the "attribute equals" selector works fine on IE7 and up, Firefox, Chrome, Opera, and Safari. (The CSS bit doesn't work on IE6, quelle shock.)
这将选择具有所需
href
属性值的a
元素,并向其添加一个类。请参阅此处的小提琴示例。That will select the
a
element with the requiredhref
attribute value, and add a class to it. See example fiddle here.