我有以下代码返回函数中每个链接的 url:
var nav_link;
$('#nav_what-we-do').find('.top-dropdown').find('a').each(function(index, elem) {
console.log("Descendant: " + elem.tagName + " " + elem.href);
the_link = $(this);
nav_link = elem.href.split('#');
if (nav_link[0] === '/what-we-do/') {
the_link.attr('href','#'+nav_link[1]);
the_link.click(function() {
var tab_id = $(this).attr('href');
selectTab(tab_id);
return false;
});
}
});
控制台打印如下链接:
Descendant: A http://localhost/testsite/what-we-do/#solutions
Descendant: A http://localhost/testsite/what-we-do/#features
Descendant: A http://localhost/testsite/what-we-do/features/test
Descendant: A http://localhost/testsite/what-we-do/solutions/test2
现在我只想要那些包含哈希 (#) 的链接并使用此哈希拆分它们。然后我想检查 array(0) 是否包含字符“/what-we-do/”。我试图像这样拆分链接:
nav_link = elem.href.split('#');
但IF部分不起作用。
有人可以告诉我我做错了什么。
编辑
根据TJ的建议
$('#nav_what-we-do').find('.top-dropdown').find('a').each(function(index, elem) {
//console.log("Descendant: " + elem.tagName + " " + elem.href);
var the_link = elem.href,
hashIndex = the_link.split("#");
if(hashIndex.length == 2) {
console.log(hashIndex);
console.log("Descendant: " + elem.tagName + " " + elem.href);
console.log('First part is: ' + hashIndex[0].indexOf("/what_we_do/"));
}
if (hashIndex.length == 2 && hashIndex[0].indexOf("/what_we_do/") !== -1) {
the_link.attr('href', "#" + hashIndex[1]);
the_link.attr('href', the_link.substring(hashIndex));
the_link.click(function() {
var tab_id = $(this).attr('href');
selectTab(tab_id);
return false;
});
}
});
如果我在控制台中打印,我会得到:
["http://localhost/testsite/what-we-do/", "solutions"] site_javascript.js:133
Descendant: A http://localhost/testsite/what-we-do/#solutions site_javascript.js:134
First part is: -1 site_javascript.js:135
["http://localhost/testsite/what-we-do/", "features"] site_javascript.js:133
Descendant: A http://localhost/testsite/what-we-do/#features site_javascript.js:134
First part is: -1
第一部分应该是值hashIndex[0].indexOf("/what_we_do/")
由于hashIndex有字符串/what-we-do/ 会发生什么?