Jquery不会全部选择

Hen*_* Mü -3 html javascript jquery select

可能重复:
jQuery id选择器仅适用于第一个元素

我想让jquery选择id = box的所有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>
Run Code Online (Sandbox Code Playgroud)

但它只选择第一个.有人能帮帮我吗?这不难吗?

Den*_*ret 14

HTML只允许一个具有给定id的元素.这就是原因(内部jQuery使用getElementById返回一个元素).

规格:

id = name [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>
Run Code Online (Sandbox Code Playgroud)


Ati*_*din 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>
Run Code Online (Sandbox Code Playgroud)