如何添加“选定的”基于 URL 的 jQuery 类?

发布于 2024-08-18 07:05:44 字数 3864 浏览 1 评论 0原文

我的 wikispace 主题中有一个侧边栏链接列表,当前使用 jQuery 根据 .com/ 之后的 URL 将类应用到每个侧边栏链接。您可以在下面的代码中看到它的应用...

<div class="WikiCustomNav WikiElement wiki"><a href="/" class="">Home</a>
<a href="/Calendar" class="calendar">Calendar</a>
<a href="/Science" class="science">Science</a>
<a href="/Language+Arts" class="language-arts">Language Arts</a>
<a href="/Video+Page" class="video-page">Video Page</a>
<a href="/Code+Page" class="code-page">Code Page</a>
<a href="/Geography" class="geography">Geography</a>
<a href="/Western+Day" class="western-day">Delicious Bookmarks</a>
<a href="/Field+Day" class="field-day">Field Day</a>
<a href="/Share+Posts" class="share-posts">Share Posts</a>
<a href="/Audio+Page" class="audio-page">Audio Page</a>
<a href="/Map+Page" class="map-page">Map Page</a>
<a href="/Staff+Olympics" class="staff-olympics">Staff Olympics</a>
<a href="/Scribd+Document" class="scribd-document">Scribd Document</a>
<a href="/Staff+Meetings" class="staff-meetings">Staff Meetings</a>
<a href="/Staff+Phone+Tree" class="staff-phone">Staff Phone Tree</a>
<a href="/Employee+Procedures" class="employee-procedures">Employee Procedures</a>
<a href="/Student+Handbook" class="student-handbook">Student Handbook</a>
<a href="/Table+Sorter" class="table-sorter">Table Sorter</a>
<a href="/Teachers+Tips" class="teachers-tips">Teachers Tips</a>

我希望它在链接中添加一个“selected”类,而不是通过基于 URL 的 jQuery 应用唯一的类,该类将被检测到例如,如果用户转到“地理”页面,jQuery 将检测该 URL 当前是否正在被查看,如果是,它会将“selected”类应用于侧边栏链接。所以,它看起来像这样...

<ul>
<li><a href="/Geography" class="selected">Geography</a></li>
<li><a href="/Map+Page">Map Page</a></li>
<li><a href="/Staff+Olympics">Staff Olympics</a></li>
<li><a href="/Scribd+Document">Scribd Document</a></li>
<li><a href="/Staff+Meetings">Staff Meetings</a></li>
<li><a href="/Staff+Phone+Tree">Staff Phone Tree</a></li>
<li><a href="/Employee+Procedures">Employee Procedures</a></li>
<li><a href="/Student+Handbook">Student Handbook</a></li>
<li><a href="/Table+Sorter">Table Sorter</a></li>
<li><a href="/Teachers+Tips">Teachers Tips</a></li>
</ul>

在我上面提供的第一个代码示例中,您可以看到其中有无序列表,只有链接。我还想知道如何将所有这些链接包装在一个无序列表中,每个链接都包含在一个列表项中,就像第二个代码示例中一样。 这相对容易吗?

我当前的侧边栏 jQuery 代码如下...

jQuery("#sidebar br").remove();
jQuery(".wiki_link, .wiki_link_new").attr('class','').each(function(){
    var className = jQuery(this).attr('href').substr(1).toLowerCase().split('+').slice(0,2).join('-');
    jQuery(this).addClass(className);
});

感谢您的帮助!

这是现在产生评论中提到的冲突的代码......

jQuery("#sidebar br").remove();
jQuery(".wiki_link, .wiki_link_new").attr("class", "").each(function () {
    var a = jQuery(this).attr("href").substr(1).toLowerCase().split("+").slice(0, 2).join("-");
    jQuery(this).addClass(a)
});

var $ul = $("<ul></ul>").insertAfter($("div#toc > h1"));
$("a[href^=#toc]").each(function () {
    var b = $("<li></li>"),
        a = $(this).parent();
    b.append(this);
    a.remove();
    $ul.append(b)
});

var loc = window.location.split("/").slice(-1);
jQuery("a.selected").removeClass("selected");
jQuery("a[href$='" + loc + "']").addClass("selected");
jQuery(".WikiCustomNav").wrapInner("<ul></ul>").find("a").wrap("<li></li>");
});

I have a sidebar list of links in my wikispace theme that currently uses jQuery to apply a class to each of the sidebar links based on the URL after the .com/. You can see this being applied in the code below...

<div class="WikiCustomNav WikiElement wiki"><a href="/" class="">Home</a>
<a href="/Calendar" class="calendar">Calendar</a>
<a href="/Science" class="science">Science</a>
<a href="/Language+Arts" class="language-arts">Language Arts</a>
<a href="/Video+Page" class="video-page">Video Page</a>
<a href="/Code+Page" class="code-page">Code Page</a>
<a href="/Geography" class="geography">Geography</a>
<a href="/Western+Day" class="western-day">Delicious Bookmarks</a>
<a href="/Field+Day" class="field-day">Field Day</a>
<a href="/Share+Posts" class="share-posts">Share Posts</a>
<a href="/Audio+Page" class="audio-page">Audio Page</a>
<a href="/Map+Page" class="map-page">Map Page</a>
<a href="/Staff+Olympics" class="staff-olympics">Staff Olympics</a>
<a href="/Scribd+Document" class="scribd-document">Scribd Document</a>
<a href="/Staff+Meetings" class="staff-meetings">Staff Meetings</a>
<a href="/Staff+Phone+Tree" class="staff-phone">Staff Phone Tree</a>
<a href="/Employee+Procedures" class="employee-procedures">Employee Procedures</a>
<a href="/Student+Handbook" class="student-handbook">Student Handbook</a>
<a href="/Table+Sorter" class="table-sorter">Table Sorter</a>
<a href="/Teachers+Tips" class="teachers-tips">Teachers Tips</a>

Instead of applying a unique class via jQuery based on the URL, I would like to have it add a class of "selected" to the link, which would be detected via the URL. For example, if the user goes to the Geography page, the jQuery would detect whether that URL was currently being viewed, and if so, it would apply the "selected" class to the sidebar link. So, it would look like this...

<ul>
<li><a href="/Geography" class="selected">Geography</a></li>
<li><a href="/Map+Page">Map Page</a></li>
<li><a href="/Staff+Olympics">Staff Olympics</a></li>
<li><a href="/Scribd+Document">Scribd Document</a></li>
<li><a href="/Staff+Meetings">Staff Meetings</a></li>
<li><a href="/Staff+Phone+Tree">Staff Phone Tree</a></li>
<li><a href="/Employee+Procedures">Employee Procedures</a></li>
<li><a href="/Student+Handbook">Student Handbook</a></li>
<li><a href="/Table+Sorter">Table Sorter</a></li>
<li><a href="/Teachers+Tips">Teachers Tips</a></li>
</ul>

In the first code sample I provided above, you can see that there is unordered list in there, only links. I would also like to know how I could wrap all of those links in an unordered list, with each link included within a list item, like in the second code example. Is that relatively easy to do?

The current jQuery code I have for the sidebar is here below...

jQuery("#sidebar br").remove();
jQuery(".wiki_link, .wiki_link_new").attr('class','').each(function(){
    var className = jQuery(this).attr('href').substr(1).toLowerCase().split('+').slice(0,2).join('-');
    jQuery(this).addClass(className);
});

Thanks for your help on this!

Here's the code that is now producing a conflict mentioned within the comments...

jQuery("#sidebar br").remove();
jQuery(".wiki_link, .wiki_link_new").attr("class", "").each(function () {
    var a = jQuery(this).attr("href").substr(1).toLowerCase().split("+").slice(0, 2).join("-");
    jQuery(this).addClass(a)
});

var $ul = $("<ul></ul>").insertAfter($("div#toc > h1"));
$("a[href^=#toc]").each(function () {
    var b = $("<li></li>"),
        a = $(this).parent();
    b.append(this);
    a.remove();
    $ul.append(b)
});

var loc = window.location.split("/").slice(-1);
jQuery("a.selected").removeClass("selected");
jQuery("a[href$='" + loc + "']").addClass("selected");
jQuery(".WikiCustomNav").wrapInner("<ul></ul>").find("a").wrap("<li></li>");
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱殇璃 2024-08-25 07:05:44

在线演示:http://jsbin.com/otapo

将测试网址粘贴到该演示页面上的文本框中要查看它,请选择相应的链接。将文本框值更改为新的 test-url 以查看它取消选择任何选定的链接,然后选择与提供的 url 相对应的新链接。

添加基于 URL 的“选定”类

var loc = window.location.split("/").slice(-1);
$("a.selected").removeClass("selected");
$("a[href$='"+loc+"']").addClass("selected");

这个特定示例需要一些解释。通常我会改变这个逻辑,并寻找同级,但考虑到您有兴趣将每个链接包装在 LI 中,这些链接将不再是同级。

我可以写这个来与每个链接周围的父 LI 一起工作,但是我不确定您是否会立即使用父 LI 对其进行测试,并认为它不起作用。话虽这么说,如果您实施以下解决方案,则可以改进该解决方案。在目前的状态下(不是很漂亮),它会以任何一种方式工作。

将链接转换为 UL

$(".WikiCustomNav").wrapInner("<ul></ul>").find("a").wrap("<li></li>");

Online demo: http://jsbin.com/otapo

Paste a test-url into the textbox on that demo page to see it select the corresponding link. Change the textbox value to a new test-url to see it deselect any selected links, and select the new link that corresponds to the url provided.

Adding Class 'Selected' Based on URL

var loc = window.location.split("/").slice(-1);
$("a.selected").removeClass("selected");
$("a[href$='"+loc+"']").addClass("selected");

This particular example here requires some explaining. Normally I would change this logic, and look for siblings, but considering the fact that you're interested in wrapping each link in an LI, these links wouldn't be siblings anymore.

I could write this to work with parent LI's around each link, but then I'm not sure if you would test it immediately with parent LI's, and think that it doesn't work. That being said, if you implement the following solution, you could improve this solution. In its current state (not very pretty), it will work either way.

Convert the Links into an UL

$(".WikiCustomNav").wrapInner("<ul></ul>").find("a").wrap("<li></li>");
梦初启 2024-08-25 07:05:44

想了解一些深层的 jQuery 魔法吗?这会将您的 div 转换为列表(jQuery 1.4+)进行类修改:

$("div.wiki").wrap("<ul>").children("a").unwrap().wrap("<li>").removeAttr("class")
  .filter("[href='" + ocation.pathname + "']").addClass("selected");

好的,这是如何工作的?它:

  • 选择div.wiki
  • 将其包装在
      中;
  • 选择
    的子级(wrap() 返回

    但*不是*);

  • 解开它们,意味着
    已删除,并且链接现在是

      的子链接;
  • 将每个链接包装在
  • 中;
  • 从链接中删除所有类;
  • 过滤到 href 等于窗口位置相对路径的链接;并将
  • selected 类添加到该链接。

Edit: Here is a fully working example that I ran locally under http://localhost/test.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  $("div.wiki").wrap("<ul>").children("a").unwrap().wrap("<li>").removeAttr("class")
    .filter("[href='" + location.pathname + "']").addClass("selected");
  $("#dump").text($("#content").html());
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div id="content">
<div class="wiki">
<a href="/one" class="wiki_link">one</a>
<a href="/test.html" class="wiki_link">two</a>
<a href="/three" class="wiki_link wiki_link_new">three</a>
</div>
</div>
<pre id="dump">
</pre>
</body>
</html>

输出:

<ul>
<li><a href="/one">one</a></li>
<li><a class="selected" href="/test.php">two</a></li>
<li><a href="/three">three</a></li>
</ul>

如果您想了解您运行的 jQuery 版本:

alert($().jquery);

编辑: jQuery 1.3 版本:

var wiki = $("div.wiki");
wiki.children("a").wrapAll("<ul>").wrap("<li>").removeAttr("class")
  .filter("[href='" + location.pathname + "']").addClass("selected")
  .end().parent().parent().insertAfter(wiki);
wiki.remove();

Want to see some deep jQuery magic? This will convert your div into a list (jQuery 1.4+) and do the class mangling:

$("div.wiki").wrap("<ul>").children("a").unwrap().wrap("<li>").removeAttr("class")
  .filter("[href='" + ocation.pathname + "']").addClass("selected");

Ok, how does this work? It:

  • Selects div.wiki;
  • Wraps it in a <ul>;
  • Selects the children of the <div> (wrap() returns the <div> still *not* the);</li>
    <li>Unwraps them, meaning the <code><div> is deleted and the links are children to the</code><ul>
    now;
  • Wraps each link in a <li>;
  • Removes all classes from the links;
  • Filters down to the link(s) that have a href equalling the relative path of the window location; and
  • Adds the selected class to that link.

Edit: Here is a fully working example that I ran locally under http://localhost/test.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  $("div.wiki").wrap("<ul>").children("a").unwrap().wrap("<li>").removeAttr("class")
    .filter("[href='" + location.pathname + "']").addClass("selected");
  $("#dump").text($("#content").html());
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div id="content">
<div class="wiki">
<a href="/one" class="wiki_link">one</a>
<a href="/test.html" class="wiki_link">two</a>
<a href="/three" class="wiki_link wiki_link_new">three</a>
</div>
</div>
<pre id="dump">
</pre>
</body>
</html>

Output:

<ul>
<li><a href="/one">one</a></li>
<li><a class="selected" href="/test.php">two</a></li>
<li><a href="/three">three</a></li>
</ul>

If you want to find out what version of jQuery you have run:

alert($().jquery);

Edit: jQuery 1.3 version:

var wiki = $("div.wiki");
wiki.children("a").wrapAll("<ul>").wrap("<li>").removeAttr("class")
  .filter("[href='" + location.pathname + "']").addClass("selected")
  .end().parent().parent().insertAfter(wiki);
wiki.remove();
素衣风尘叹 2024-08-25 07:05:44

听起来你需要做这样的事情:

$(".wiki_link").removeClass("wiki_link");   // remove the css class
$(".wiki_link_new").removeClass("wiki_link_new");

// adds the selected class to the link who's href attribute contains 
// the current relative path.  Probably needs tweaking based on querystrings
// and whatnot.
$(".wiki_link[href~=" + window.location.pathname +"]").addClass("selected");  

如果所有链接都有相同的两个类(wiki_link 和 wiki_link_new),你可以通过执行 removeClass("wiki_link wiki_link_new") 一次性删除它们。

Sounds like you need to do something like this:

$(".wiki_link").removeClass("wiki_link");   // remove the css class
$(".wiki_link_new").removeClass("wiki_link_new");

// adds the selected class to the link who's href attribute contains 
// the current relative path.  Probably needs tweaking based on querystrings
// and whatnot.
$(".wiki_link[href~=" + window.location.pathname +"]").addClass("selected");  

If all the links have the same two classes (wiki_link and wiki_link_new) you can remove them both at once by doing removeClass("wiki_link wiki_link_new").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文