开发者

Match url folders with a tag href to make an active state

I made an active state for my menu on a certain urls. I have urls like this: 开发者_开发知识库

  • /products/other-clothing/sporting/adults-anzac-australia-polo
  • /products/other-clothing/sporting/adults-nz-tee
  • /products/bags/backpacks

My code gets the folder from after the / so other-clothing, sporting, etc. It is working fine, I just assume there is a more efficient way to write the code.

Here is my code:

jQuery(".product-nav li a").each(function() {
  // URL url
  var cat = location.pathname.split("/")[2];
  var subcat = location.pathname.split("/")[3];
  var c = "/products/" + cat + "/" + subcat;

  // A tag url
  var acat = this.href.split("/")[4];
  var asubcat = this.href.split("/")[5];
  var e = "/products/" + acat + "/" + asubcat;

  if(e == c) {
    jQuery(this).parent().addClass("active");
    jQuery(this).parent().parent().parent().addClass("active");
  }
});

If anyone can provide a cleaner way of writing the code that'd be great. I probably dont need "/products/" +.


Notice the output of the following expressions:

$('<a href="/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state"></a>')[0].href;
/*
 * http://stackoverflow.com/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state
 */
$('<a href="/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state"></a>').eq(0).attr('href');
/*
 * /questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state
 */

So, if your <a> tags contain URLs that start with / then you can compare the .attr('href') with location.pathname. For testing, try running this in console from this page:

$('a').each(function () {
    if ($(this).attr('href') == location.pathname) {
        $(this).css({
            'font-size': '40px',
            'background-color': 'lime'
        });
    }
});


Here's a brief whack at it:

jQuery(".product-nav li a").each(function() {
  // URL url
  var c = location.pathname.split('/').slice(2, 4)
  // A tag url
    , e = this.href.split('/').slice(4, 6)
  ;

  if(e[0] == c[0] && e[1] == c[1]) {
    jQuery(this).parentsUntil(
      'div:not(.subnav)', // go up the tree until the 1st div that isn't .subnav
      '.product-nav li, .subnav' // and only match these parents
    ).addClass('active');
  }
});

.parent().parent().parent()... has a pretty bad code smell to it but can't be improved without a look at your markup. You should probably be using .closest() instead.


Interesting question. Here is my attempt to clean it up:

jQuery(function ($) {
  function Category(outer, inner) {
    this.outer = outer
    this.inner = inner
  }

  Category.fromURL = function (url) {
    var parts = url.replace(/^(https?:\/\/.*?)?\//, "").split("/")

    return new Category(parts[1], parts[2])
  }

  Category.prototype.equals = function (other) {
    return this.outer === other.outer
      && this.inner === other.inner
  }

  var category = Subcategory.fromURL(location.href)

  $(".product-nav a").each(function () {
    if (Category.fromURL(this.href).equals(category)) {
      $(this).closest("li.inner").addClass("active")
      $(this).closest("li.outer").addClass("active")
    }
  })
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜