简体   繁体   中英

Why the toggle is not working with other DIVs?

Here i have a fiddle link ! The problem is only 1st top div is working..

[http://jsfiddle.net/5Ux8L/4/][1]

HTML-

 <div id="top">top </div>
    <div id="box">box </div>
 <div id="top">top </div>
    <div id="box">box </div>

jQuery-

$(document).ready(function(){
  $("#top").click(function (){
        $("#box").toggle();
    });
});

Use common class instead of ids, you should not have duplicate ids .

$(document).ready(function(){
  $(".top").click(function (){
        $(this).next().toggle();
    });
});

You cannot have elements with the same id. Change top from an id to a class .

HTML

 <div class="top">top </div>
 <div class="box">box </div>
 <div class="top">top </div>
 <div class="box">box </div>

Javascript

$(document).ready(function(){
  $(".top").click(function (){
        $(this).next(".box").toggle();
    });
});

JS Fiddle: http://jsfiddle.net/5T3K2/

Id of an element must be unique, so use class instead

<div class="top">top</div>
<div class="box">box</div>
<div class="top">top</div>
<div class="box">box</div>

then

jQuery(function ($) {
    $(".top").click(function () {
        $(this).next().toggle();
    });
});

Demo: Fiddle

$(document).ready(function(){
$(".top").click(function (){
    $(this).next(".box").toggle();
});
});

http://jsfiddle.net/5Ux8L/5/

Don't use id name for multipal divs. Always use class. By the way here is your working code.

 <div class="top">top </div>
    <div class="box">box </div>
 <div class="top">top </div>
    <div class="box">box </div>

jQuery

$(document).ready(function(){
  $(".top").click(function (){
        $(this).next().toggle();
    });
});

Demo

Use class instead of Id . Id is unique property. fiddle

 <div class="top">top </div>
    <div class="box">box </div>
 <div class="top">top </div>
    <div class="box">box </div>

$(document).ready(function(){
  $(".top").click(function (){
        $(".box").toggle();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM