我如何使用jquery函数到多个div

时间:2012-08-10 09:40:28

标签: javascript jquery

我希望使用JavaScript / DOM属性为<div>设置显示/隐藏功能。

将JavaScript onclick()与两个按钮showhide一起使用,每个按钮位于自己的<div>中,它的工作方式如下:

  • 默认情况下,隐藏show按钮,显示主<div>和隐藏按钮。点击hide按钮隐藏主<div>和“隐藏”按钮本身,显示show按钮。
  • 点击show按钮会显示主<div>,“显示”按钮会显示hide按钮我认为可以使用document.getElementById(DIVid).style.visibility="hidden"之类的内容实现这一目标。

但我该怎么做?

4 个答案:

答案 0 :(得分:3)

$('#hidebutton').click(function() {
   $('#DIVid, #showbutton').show();
   $(this).hide();
});

$('#showbutton').click(function() {
   $('#DIVid, #hidebutton').show();
   $(this).hide();
});

或者如果你想:

$('#hidebutton, #showbutton').click(function() {
    var show = $(this).is('#showbutton');
    $('#DIVid, #hidebutton').toggle(show);
    $('#showbutton').toggle(!show);
});

答案 1 :(得分:1)

为每个<div>定义一个类,并为其创建jQuery函数。这是示例代码:

<div class="a"></div>
<div class="a"></div>
<div class="a"></div>

Jquery code

$(".a").click(function(e){
your code goes here
}

答案 2 :(得分:0)

请检查:see Demo

$("#btnclk").click(function() {
    if ($('.test').is(':visible')) {
        $(".test").hide();
    } else {
        $(".test").show();
    }
});

<div class="test">
  Div1
</div>
<div class="test">
  Div1
</div>

<input type="button" id="btnclk" value="Show/Hide">

或者,如果您想使用JavaScript,请使用getElementsByClassName代替getElementById

答案 3 :(得分:0)

jsBin demo

简单的jQuery:

$('.show_hide').click(function(){
  $(this).text( $(this).text()==='HIDE'?'SHOW':'HIDE' );
  $(this).next('.box_content').stop().slideToggle();
});

HTML:

  <div class="box">
    <h2>Title 1</h2><button class="show_hide">HIDE</button>
    <div class="box_content">
      <p>
        1 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tempus tortor at nisl dictum lobortis. Mauris dolor augue, porttitor non cursus et, hendrerit sed mi. Morbi sollicitudin sodales dui, et interdum justo condimentum vel.
      </p>

    </div>
  </div>

CSS:

.box{
  position:relative;
  padding:15px;
  background:#eee;
  margin:10px;
}
.box h2{
  margin:0px;
  padding:5px;
}
.show_hide{
  position:absolute;
  right:15px;
  top:20px;
  cursor:pointer;
}