2012-12-20 145 views
-3

可能重複:
jQuery id selector works only for the first elementjQuery的不選擇所有

我希望jQuery選擇使用id =箱的所有div:

<!DOCTYPE html> 
    <head> 
    <link rel="stylesheet" href="css/main.css" type="text/css"/> 
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script> 
    <script src="js/sizer.js"></script> 
     <title> 
     Design tests 
     </title> 
    </head> 
    <body> 
     <div id="box" style="width:300px;"> 
     Hallo 
     </div> 

     <div id="box" style="width:300px;"> 
     Hallo 
     </div> 

    <script>  
    $(document).ready(function(){ 
     $("#box").mouseenter(function(){ $(this).css("border", "1px gray outset");}).mouseleave(function(){ $(this).css("border", "none");}); 
    }); 
    </script> 
    </body> 
</html> 

但它只選擇第一個。有人能幫幫我嗎?這不難嗎?

+0

它的人有一個刺是什麼。免費代表! – andrewk

+8

爲什麼所有的downvotes?僅僅因爲一個基本問題並不意味着它是不好的。 –

+0

LoL,你不能有多個id。改爲使用類名稱。 '

'然後'$( 「箱子」)' – SpYk3HH

回答

14

HTML只允許一個給定的id元素。這就是原因(內部jQuery使用返回一個元素的getElementById)。

the spec

ID =名[CS]

該屬性分配一個名稱的元素。該名稱在文檔中必須是唯一的。

如果你要選擇一個以上的元素,使用類,而不是一個ID:

<div class="box" style="width:300px;"> 
    Hallo 
    </div> 

    <div class="box" style="width:300px;"> 
    Hallo 
    </div> 

<script>  
$(document).ready(function(){ 
    $(".box").mouseenter(function(){ $(this).css("border", "1px gray outset");}).mouseleave(function(){ $(this).css("border", "none");}); 
}); 
</script> 
+1

笑免費代表! :-) –

+0

@AtifMohammedAmeenuddin編號:我很久以前就通過了代理權。 –

+0

啊,我知道。我希望我能很快就會有.. –

6

你不能有超過1個相同的ID,使用一個類來代替

<!DOCTYPE html> 
    <head> 
    <link rel="stylesheet" href="css/main.css" type="text/css"/> 
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script> 
    <script src="js/sizer.js"></script> 
     <title> 
     Design tests 
     </title> 
    </head> 
    <body> 
     <div class="box" style="width:300px;"> 
     Hallo 
     </div> 

     <div class="box" style="width:300px;"> 
     Hallo 
     </div> 

    <script>  
    $(document).ready(function(){ 
     $(".box").mouseenter(function(){ $(this).css("border", "1px gray outset");}).mouseleave(function(){ $(this).css("border", "none");}); 
    }); 
    </script> 
    </body> 
</html> 
2

你選擇改變div#box,它會工作像這樣

$(document).ready(function(){ 
    $("div#box").mouseenter(function(){ $(this).css("border", "1px gray outset");}).mouseleave(function(){ $(this).css("border", "none");}); 
}); 

另請注意,具有相同ID的多個元素是不好的做法。

+0

哈哈+1,你是冠軍! –

2

語法$(「#箱」)是指去選擇第一個元素的ID相匹配的「盒子」。你想要做什麼用類代替,或者如果你堅持要用ID $(「DIV [ID =‘盒子’]」)會做你想要