为什么不jQuery在两个同名的ID上工作?

时间:2015-07-31 10:33:51

标签: jquery

我有.ims和.content,两个ID但我的代码仅用于父ID #one

<html>
    <div id="one">
        <div id="ims">show some content</div> 
        <div id="content"> hello world</div> 
    </div>
    <div id="two">
        <div id="ims">show some content</div> 
        <div id="content"> hello world</div> 
    </div>
    <script>
        $(document).ready(function () {
            $("#content").hide();
            $("#ims").click(function () {
                $("#ims").slideUp("slow");
                $("#content").slideDown("slow");
            });
        });
    </script>
</html>

2 个答案:

答案 0 :(得分:3)

您对不同的元素使用相同的idid必须是唯一的。请改用class

<强> HTML

<div id="one">
    <div class="ims">show some content</div> 
    <div class="content"> hello world</div> 
</div>
<div id="two">
    <div class="ims">show some content</div> 
    <div class="content"> hello world</div> 
<div>

<强>的jQuery

$(document).ready(function(){
    $(".content").hide(); // Hide all .contents
    $(".ims").click(function(){
        $(this).slideUp("slow").siblings(".content").slideDown("slow"); // Hide current ims & show sibling with class content
    });
});

Fiddle

答案 1 :(得分:1)

Id应该是唯一使用class而不是id

<强> HTML

<div id="one">
    <div class="ims">show some content</div>
    <div class="content">hello world</div>
</div>
<div id="two">
    <div class="ims">show some content</div>
    <div class="content">hello world</div>
    <div>

<强> JS

$(document).ready(function () {
    $(".content").hide();
    $(".ims").click(function () {
       $(this).slideUp("slow").next(".content").slideDown("slow");
    });
});

<强> DEMO