I have a menu with multiple jQu开发者_JAVA技巧ery toggles in it and I wanted to have jQuery toggle open one if the page URL matched. I guessed that I would need an array to keep the code short, but I know I'm doing something wrong.
$(function() {
var pathname = window.location.pathname;
var myWhoweare = new Array("history.asp","corporate_profile.asp");
if(jQuery.inArray(pathname, myWhoweare) !== -1) {
$('div.accordian_whoweare> div').show();
}
});
I'm pretty sure that my error is in how the array is created (there are two URLs in it for this test, there will be more later) and detected.
Any help would be appreciated.
location.pathname
has a forward slash as first character. Add it to the URLs in your array (and use array literal notation):
$(function() {
var pathname = window.location.pathname;
var myWhoweare = ["/history.asp","/corporate_profile.asp"];
if($.inArray(pathname, myWhoweare) !== -1) {
$('div.accordian_whoweare> div').show();
}
});
If you are going to add more URLs, more efficient would be to use a map (or hash table, however you want to call it), realised by a JavaScript object:
$(function() {
var pathname = window.location.pathname;
var myWhoweare = {
"/history.asp": true,
"/corporate_profile.asp": true
};
if(myWhoweare[pathname]) {
$('div.accordian_whoweare> div').show();
}
});
Testing whether the URL is contained in the map will be O(1)
(whereas the runtime for finding a value in the array will obviously be higher).
精彩评论