我有一个看起来像这样的列表:jQuery:为什么这个选择器只在某些时候工作?
<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);
}
但是,如果“当前页面项目”是在列表的开始(即它没有“较高”的兄弟姐妹,只是一个“较低”的),这段代码从不执行。为什么?它没有任何反应。如果“当前页面项目”位于列表的结尾,则一切正常。
此外,奖金Q:“==未定义”从不起作用。为什么? Javascript中的isset是什么?
这并没有真正回答吧:)他问为什么他的'== undefined'不工作。 ..原因不仅仅是比较,它是在未定义的'.length'检查到达之前爆发。 – 2010-10-23 10:53:30
他还问JavaScript中isset是什么。我不知道PHP(我假设),但我相信上面的代码是检查是否设置了某些东西的正确方法。 – 2010-10-23 11:04:00