2010-11-16 14 views
0

我有了這個功能把A HREF點擊功能成的if-else語句

$("a[href*=/category/movies/]").click(function() { 
so.addVariable('stretching','fill'); 
so.write('mediaspace'); 
}); 

,我想變成一個if ... else語句。

如何在div#header_playlist_categories 中定位鏈接並應用else語句,如果鏈接指向「/ categories/movies /」以外的鏈接?

回答

1

我想你想要做的是什麼處理div#header_playlist_categories內的a元素的所有點擊。如果鏈接的href屬性包含/category/movies/,則您希望做一件事,如果鏈接的屬性不包含,則另一件事。如果是這樣,你可以做到這一點很好地利用delegate()

$('#header_playlist_categories').delegate('a', 'click', function(e) { 
    e.preventDefault(); // I imagine you always want to disable the default action 

    if (this.href.indexOf('/category/movies/') !== -1) { 
     so.addVariable('stretching','fill'); 
     so.write('mediaspace'); 
    } else { 
     // do whatever else you want to do 
    } 
}); 
+0

謝謝你的信息。我可能會再次使用這個! – PHearst 2010-11-16 19:10:41

0

您可以使用:not()這樣得到其他鏈接:

$("#header_playlist_categories a:not([href*=/category/movies/])").click(function() { 
    //something else 
}); 

還是有點便宜,檢查循環:

$("a").each(function() { 
if(this.href.indexOf("/category/movies/") !== -1) { 
    $(this).click(function() { 
    so.addVariable('stretching','fill'); 
    so.write('mediaspace'); 
    }); 
} else { 
    $(this).click(function() { 
    //something else 
    }); 
} 
}); 
+0

謝謝,便宜的版本爲我工作 – PHearst 2010-11-16 19:09:09

0

你應該delegate that eventdiv#header_playlist_categories

在你的回調函數中,訪問被點擊的鏈接的「href」屬性並根據它的值分支你的處理程序。