最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery OnClick show nearest div class not showing - Stack Overflow

programmeradmin0浏览0评论

I have a list of buttons and a div under each which I need to show when the user clicks each button.

This is what I'm trying, but nothing is happening.

jQuery

<script>
         $( document ).ready(function() {
            $(this).click(function() {
                $(this).closest(".mainbutton").show();
            });
         });
</script>

Html

<a class="mainbutton" role="button">click me</a>
 <div class="mydiv" style="display:none;">
   <h1>I was hidden</h1>
 </div>

I have a list of buttons and a div under each which I need to show when the user clicks each button.

This is what I'm trying, but nothing is happening.

jQuery

<script>
         $( document ).ready(function() {
            $(this).click(function() {
                $(this).closest(".mainbutton").show();
            });
         });
</script>

Html

<a class="mainbutton" role="button">click me</a>
 <div class="mydiv" style="display:none;">
   <h1>I was hidden</h1>
 </div>
Share Improve this question edited Jul 2, 2014 at 9:48 kamesh 2,4143 gold badges27 silver badges33 bronze badges asked Jul 2, 2014 at 9:40 Satch3000Satch3000 49.5k90 gold badges225 silver badges349 bronze badges 3
  • You are binding events to the document.. – Rajaprabhu Aravindasamy Commented Jul 2, 2014 at 9:41
  • You want to show div direct under the button only single div will show? – Yogesh Sharma Commented Jul 2, 2014 at 9:41
  • In your Jquery what is mean by $(this) in $(this).click( function – Yogesh Sharma Commented Jul 2, 2014 at 9:42
Add a ment  | 

6 Answers 6

Reset to default 7

I'm not so sure what you try to achieve but I guess what you would like to do is something like this:

 $(".mainbutton").click(function() {
    $(this).siblings(".mydiv").show();
 });

Hope this helps.

Try:

$(".mainbutton").click(function() {
    $(this).next("div").show();
});

closest() traverses UP the DOM tree!

Try this:

$( document ).ready(function() {
$(".mainbutton").click(function() {
    $(this).next(".mydiv").show();
 });
 });

I guess that u want

$( document ).ready(function() {

        $('.mainbutton').on('click',function() {
               $(this).siblings(".mydiv").show();
        });

 });

I don't know exact your requirement but I think you want to do something like this

Please see Demo

 $( document ).ready(function() {

            $(".mainbutton").click(function() {
                $(this).next(".mydiv").show();
            });

         });

you can simple use this

$( document ).ready(function() {
     $(".mainbutton").click(function() {
         $(".mydiv").css("display", "inherit");
       });
    });
发布评论

评论列表(0)

  1. 暂无评论