修改click事件脚本以使其更具体

时间:2010-07-17 13:29:41

标签: javascript jquery

我需要修改以下函数,以便它只将click事件绑定到所有href的= /ShoppingCart.asp?ProductCode="whatever“(无论=在那里是什么”)但不是它特别是/ShoppingCart.asp?ProductCode="GFT“。它还必须检查或转换gft或Gft到大写以检查那些。所以基本上它必须检查GFT的情况的任何变化。 如果找到“GFT”,则不绑定click事件。

function sacsoftaddtocart() {
    if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
        $("a[href^='/ShoppingCart.asp?ProductCode']").click(function () {
            var href = $(this).attr('href');
            addToCart3(href);
            return false;
        });
    }
}   

2 个答案:

答案 0 :(得分:1)

您可以使用.toUpperCase().filter()执行此操作,如下所示:

function sacsoftaddtocart (){
  if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
    $("a[href^='/ShoppingCart.asp?ProductCode']").filter(function() {
       return this.href.length - this.href.toUpperCase().indexOf('PRODUCTCODE=GFT') != 15;
    }).click(function () {
      var href = $(this).attr('href');
      addToCart3(href);
      return false;
    });
  }
}

You cant test it in a demo herethis.href.length - matchPosition == 15检查ProductCode=GFT是否匹配在“GFT”之后没有任何内容,因此像“GFT5”这样的产品代码将不匹配。

答案 1 :(得分:0)

使用此帖link text

中的过滤器
function sacsoftaddtocart() {
    if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
        $("a:regex('href','*/ShoppingCart.asp\?ProductCode=(!?=GFT)*)").click(function () {
            var href = $(this).attr('href');
            addToCart3(href);
            return false;
        });
    }
}

或者如果您不想使用exrat插件:

function sacsoftaddtocart() {
    if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
        $("a['href^='/ShoppingCart.asp?ProductCode']")
            .filter(function(){ return !/ProductCode=GTF/.test($(this).attr('href')) };
            .click(function () {
                var href = $(this).attr('href');
                addToCart3(href);
                return false;
        });
    }
}

尝试一下,看看会发生什么;)