使用 jquery 将链接片段与 url 片段进行匹配?
如何在链接片段中找到与 url 片段的匹配项,然后突出显示该链接的父链接?
HTML、
<div class="item">
<a href="http://example.come/#/story/article-1/">Link 1</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-2/">Link 2</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-3/">Link 3</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-4/">Link 4</a>
</div>
jquery,
//var fragment = location.hash;
fragment = '#/story/article-3/';
string = $('.item').find('a').attr('href');
array_string = string.split('#');
last_item = array_string[array_string.length - 1];
if(fragment == '#'+last_item)
{
alert('match!');
// this is my theory... but I don't know how to get the object that matches the fragment.
match_object.parents().css({background:'red'});
}
因此,在本例中,Link 3 的容器元素应突出显示。
How can I find the match in a link's fragment with the url's fragment and then highlight the link's parent?
HTML,
<div class="item">
<a href="http://example.come/#/story/article-1/">Link 1</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-2/">Link 2</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-3/">Link 3</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-4/">Link 4</a>
</div>
jquery,
//var fragment = location.hash;
fragment = '#/story/article-3/';
string = $('.item').find('a').attr('href');
array_string = string.split('#');
last_item = array_string[array_string.length - 1];
if(fragment == '#'+last_item)
{
alert('match!');
// this is my theory... but I don't know how to get the object that matches the fragment.
match_object.parents().css({background:'red'});
}
So, in this case, the Link 3's container element should be highlighted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
优雅的最短解决方案
现场演示
另一个不太优雅的选择,但一个例子说明了为什么你的代码没有按预期工作。
现场演示 2
如果不使用
.each
你只会获取第一个链接的 href,因此它永远不会与另一个链接匹配。所以基本上我只是把你的逻辑包裹起来,并稍微修改你的选择器以将 div 背景变成红色。不过我推荐选项一。Elegant shortest solution
Live Demo
Another less elegant option but an example of why your code wasn't working as expected.
Live Demo 2
Without using
.each
you will only get the href for the first link, so it can never match the other. So basically I just took your logic wrapped it with each, and modified your selector a bit to turn the div background red. I recommend option one however.只需过滤掉与我们的片段不匹配的链接并应用CSS。
演示
Just filter out the links that don't match our fragment and apply css.
DEMO
两个建议。
首先,您可能不需要所有循环。看一下属性以选择器结尾。这也许能够为您完成搜索。
一旦你匹配了,那么你应该能够做这样的事情:
Two suggestions.
First, you may not need all that looping. Take a look at the Attribute Ends With Selector. That may be able to accomplish the search for you.
Once you have the match, then you should be able to do something like this: