2012-12-20 148 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 =‘盒子’]”)会做你想要