我有一个如下所示的列表:
<li class = "current_parent level-0">
<a> Parent Link </a>
<ul class= "children">
<li class = "level-1">
<a> Link to child </a>
</li>
<li class = "level-1 current_page_item">
<a> Link to child </a>
</li>
<li class = "level-1">
<a> Link to child </a>
</li>
</ul>
</li>
我还有一些jQuery来查找“当前页面项目”的兄弟姐妹,并从中获取一些信息(标题和URL)。在上面的示例中,“当前页面项目”两侧都有两个兄弟姐妹,代码效果很好:
//Get URLs, run a length check against them. Execute functions are necessary. Pass the functions the relevant URL
var nextURL= $(".current_page_item").next().find("a").attr("href"); //Get the HREF of the next page in list
var previousURL= $(".current_page_item").prev().find("a").attr("href"); //Get the HREF of the previous page in list
if(previousURL.length >= 1){
alert ("Setting prev URL!");
setPrevPageLink(previousURL);
}
else if(previousURL == undefined){
alert ("Hiding prev URL!");
$('.previous_link').hide();
}
if (nextURL.length >= 1){
alert ("Setting next URL!");
setNextPageLink(nextURL);
}
else if(nextURL == undefined){
alert ("Hiding Next URL!");
$('.next_link > a').hide();
}
function setPrevPageLink(previousURL) {
var prevTitle = $(".current_page_item").prev().find("a").attr("title"); //Get the title of previous page in list. WP provides.
$(".previous_link > a").attr("href", previousURL); //Set the 'Previous Link' to the URL of the previous item in list.
$(".previous_link > a").text(prevTitle); // Set the Title Text of the Link to the title of the previous Item in the List
alert ("Previous URL is" + previousURL + "and it's title is " + prevTitle + "and it's length is " + previousURL.length); //Drop an alert for Debug
}
function setNextPageLink(nextURL){
var nextTitle = $(".current_page_item").next().find("a").attr("title");
$(".next_link > a").attr("href", nextURL);
$(".next_link > a").text(nextTitle);
alert ("Next URL is" + nextURL + "and the title is" + nextTitle + "and it's length is" + nextURL.length);
}
但是,如果“当前页面项目”位于列表的START(即,它没有“更高”的兄弟,只是“更低”的兄弟),则此代码永远不会执行。为什么?没有任何事情发生在它。如果“当前页面项目”位于列表的END,则一切正常。
此外,奖金问:“== undefined”永远不会奏效。为什么? Javascript中的等值是什么?
答案 0 :(得分:2)
这是因为如果没有获取previousURL
的链接,undefined
将为href
,因此您需要在之前检查undefined
检查属性的.length
,如下所示:
if(previousURL === undefined){
alert ("Hiding prev URL!");
$('.previous_link').hide();
}
else if(previousURL.length >= 1){
alert ("Setting prev URL!");
setPrevPageLink(previousURL);
}
确保对nextURL
执行相同的操作。我认为你的困惑来自一个糟糕的测试,如果它在列表末尾,那么会爆炸,you can test it here。
答案 1 :(得分:0)
回答红利问题:
检查成员是否未定义:
typeof x === "undefined"