2014-03-31 50 views
0

我正在使用jQuery來查找具有特定ID的div,但它返回空值。這很奇怪,因爲試圖找到其他的div工作得很好。jQuery無法找到指定ID的div

jQuery的

$(document).ready(function() 
{ 
    //Finds parent div without a problem 
    console.log($('#next-sheet')); 

    //Returns null, can't find the div I really need 
    console.log($('#start-course')); 

    //Also returns null 
    console.log($('#next-button')); 

    //Still returns null, can't find the div 
    console.log($('#next-sheet #start-course')); 
}); 

HTML

<div id='next-sheet'> 
    <a href="/courses/start/<?php echo $data['Courses']['Course']['id']; ?>" class='right disable-hover'> 
     <div class='button' id='start-course next-button' data-callbackdata="<?php echo $data['Courses']['Course']['name']; ?>" >Start Course</div> 
    </a> 
    <div class="clear"></div> 
</div> 

這是很奇怪的,我現在用的。就緒功能,所以HTML是可用的,因爲它可以尋父DIV 。但是當我試圖找到孩子div時,它找不到任何東西。

與所有其他東西一樣,jQuery加載正確。這只是靜態的HTML。我正在使用CakePHP,但這應該不是問題。

有什麼我在這裏失蹤?

+0

這是一個問題'id ='start-course next-button''從標識中刪除'next-button' – Pavlo

+0

不應該使用空格,原因很簡單,空格字符不適用於ID屬性。 – Satpal

+0

HTML5允許空格和更多字符作爲ID,但空間需要在選擇器中轉義。 '$(「start-course \\ next-button」)' –

回答

6

由於id是獨一無二的,你只能有一個元素一個id,所以要用:

id='start-course' 

或:代替

id='next-button' 

id='start-course next-button' 
+0

好的,那確實是個問題。謝謝。 – DijkeMark

+0

@DijkeMark:如果你找到了答案的解決方案,然後點擊ANSWER來解決這個問題。 – dreamweiver

+0

我會在8分鐘內,我不能做更早 – DijkeMark

1

你可以對同一元素沒有多個ID -

id='start-course next-button' // this is wrong 

雖然可以有多個歸類這樣的 -

class='button start-course next-button' // you will need to replace # with . 
+0

好吧,這確實是問題。我一直認爲你可以使用多個ID,只要它們是唯一的。我想不是當試圖通過ID檢索div時。在css中使用多個id可以正常工作。謝謝! – DijkeMark

0

您也可以嘗試選擇

$("element[id$='txtTitle']") 

$("div[id$='next-button']") 
2

ID和 「以結束」名稱令牌必須以字母([A-Za-z])開頭可能是 後跟任意數量的字母,數字([0-9]),連字符(「 - 」), 下劃線(「_」),冒號(「:」)和句點(「。」)。

id ='start-course next-button'is NOT OK。與啓動course_next按鈕

嘗試,如果你想找到一個以上的「名稱」使用類

<div class="class1 class2"/> 

控制這應該是OK

console.log($('.class1')); 
    console.log($('.class2')); 
    console.log($('.class1.class2')); 
+0

這應該是正確的答案... –