检查URL中的重复项

时间:2012-10-15 21:34:35

标签: jquery duplicates

  

可能重复:
  Check if URL contains href of link I already clicked

我的一些网址导致了这个:

mydomain.com/t-shirts+white+white

有没有办法过滤掉???

Jquery的:

$('#coll-filter li a').one('click', function () {
  jQuery(this).attr("href", window.location.href  + '+' +$(this).attr('href'));
    jQuery('#coll-filter li a').each(function() { 
       if (window.location.href.indexOf($(this).attr('href')) != -1) {
             alert("no")
         }

    });

 });

1 个答案:

答案 0 :(得分:1)

这会删除重复的过滤器:

function removeDupFilters(str) {
    var pos = str.search(/\/.*?$/), path, items, map = {}, i;
    if (pos !== -1) {
        path = str.substr(pos + 1);
        items = path.split("+");
        for (i = 0; i < items.length; i++) {
            map[items[i]] = true;
        }
        items = [];
        for (i in map) {
            items.push(i);
        }
        return str.substr(0, pos + 1) + items.join("+");
    }
    return str;
}

工作演示:http://jsfiddle.net/jfriend00/ntb8f/

在您的代码中使用它,它将是:

$('#coll-filter li a').one('click', function (e) {
    var url = removeDupFilters(window.location.href + '+' + $(this).attr('href'));
    if (url !== window.location.href) {
        // go to the new URL
        window.location.href = url;
    }
    e.preventDefault();
});

或者,您可以直接检查当前网址而不使用此功能:

$('#coll-filter li a').one('click', function (e) {
    var filter = $(this).attr('href');
    var re = new RegExp("/|\\+" + filter + "$|\\+", "i");
    if (!re.test(window.location.href)) {
        // go to the new URL
        window.location.href = window.location.href + "+" + filter;
    }
    e.preventDefault();
});