开发者

JQuery: Click to Hide DIV, how can I make one function to click and hide individual divs?

开发者 https://www.devze.com 2023-03-11 00:43 出处:网络
I have multiple divs like setted up below. I want 1 (one) JQuery function that onclick of ahref (.hide), Hide the data inside the <div class=\"data\">.

I have multiple divs like setted up below. I want 1 (one) JQuery function that onclick of ahref (.hide), Hide the data inside the <div class="data">.

1. This should be 1 function that can hide multiple DIV's

2. An 开发者_StackOverflowexplanation would be great if using the jquery this selector, I suspect this is what I need.

3.Keep it simple!

4. Also a nice sliding toggle effect would be great, to slide up and down on click.

I attempted this, but I had to make different jquery code for each div, which is... long..

Thanks for any help!! and hopefully correct answers!!

<div id="uniqueDiv1" class="frame">
    <a href="#" class="hide">Hide</a> // On click of this Div
        <div class="data">
            <pre>data</pre>           // Hide This Div or Data
        </pre>
</div>

<div id="uniqueDiv2" class="frame">
    <a href="#" class="hide">Hide</a> // On click of this Div
        <div class="data">
            <pre>data</pre>           // Hide This Div or Data
        </pre>
</div>


<remember> I want 1 simple Jquery DOM function for all Multiple Divs </remember>


You could it like this:

$('div.frame a.hide').click(function(e){
   e.preventDefault();
   $(this).next('div.data').toggle(); 
});

http://jsfiddle.net/niklasvh/QbDMs/

  • The $('div.frame a.hide') selects all the "hide" links.
  • The e.preventDefault(); prevents the default link action
  • The $(this).next('div.data').toggle(); selects the next div with class="data" and toggles its visibility

edit - You didn't mention this, but if you want to toggle the text on the button as well, you could add:

if ($(this).text()=='Show'){
     $(this).text('Hide');   
    }else{
     $(this).text('Show');   
}

making the final code look like:

$('div.frame a.hide').click(function(e){
   e.preventDefault();
   var div =$(this).next('div.data').slideToggle(); 
    if ($(this).text()=='Show'){
     $(this).text('Hide');   
    }else{
     $(this).text('Show');   
    }
});


$("a.hide").click(function(){
   $(this).parent().find(".data").slideToggle();
});

This should work. this refers to the item clicked. It simply finds the .data within the parent div and slideToggles it.

fiddle: http://jsfiddle.net/yJfbP/

NOTE: Your html in your post is malformed. You have </pre> where you should be ending a div.


$(document).ready(function(){
    $('.hide').click(function()) {
        $(this).next().hide();
    });
});


Try this:

$(".frame .hide").click(function(){
    var $this = $(this);
    var txt = $this.text();
    if(txt == "Hide"){
        $this.text("Show");
    } else {
        $this.text("Hide");
    }
    $this.next(".data").toggle();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消