<div class="item text-center">
<div class="class1"> <p> Something </p> </div>
</div>
<div class="item text-center">
<div class="class1"> <p> Something </p> </div>
</div>
$(".class1").hide();
$(".item").click(function () {
$(".class1").show();
})
I want that when the user click div of item, its own class1 should be show(); But in my codes, when the user click item of div, all class1 shows.
How can i do that just own class can be shown?
To fix this you need to use DOM traversal to access the .class1
element(s) within the clicked .item
. To do that you can use the this
keyword within the event handler to access the element which raised the event. Try this:
$(".item").click(function() { $(this).find(".class1").show(); })
.class1 { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="item text-center"> Foo <div class="class1"> <p> Something </p> </div> </div> <div class="item text-center"> Bar <div class="class1"> <p> Something </p> </div> </div>
Note in the example that I used CSS to hide the .class1
elements instead of JS. This is because JS runs after the DOM has loaded, so can result in elements being visible for a short time before they are hidden. CSS runs before this, so avoids that occurrence.
$(".class1").hide(); $(".item").click(function () { $(this).find(".class1").show(); });
<,--The parent divs should not be empty. otherwise when later in the code you call the,hide () method on their respective child divs: there would be nothing left to click on--> <div class="item text-center"> item1 <div class="class1"> <p> Something </p> </div> </div> <div class="item text-center"> item2 <div class="class1"> <p> Something </p> </div> </div> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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.