我有一個看起來像這樣的列表: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