jquery show hide使用href标签

use*_*794 0 html jquery

我有一些jquery根据按下哪个按钮显示和隐藏新的div.而不是按钮我想插入我自己的文本/图像,让他们以相同的方式工作,揭示和隐藏新窗口.

这是jquery:

<script>
    $(document).ready(function(){

        $(".buttons").click(function () {
        var divname= this.value;
          $("#"+divname).show("slow").siblings().hide("slow");
        });

      });
</script> 
Run Code Online (Sandbox Code Playgroud)

这是我希望更改为aa href标签的其中一个按钮的代码.

<input type="button" id="button1" class="buttons" value="div1"></input>
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.谢谢.皮娅

dou*_*arp 5

您可以使用jQuery data()方法 - http://api.jquery.com/data/ - 在anchor元素(div ID)上存储任意数据,然后使用该值显示正确的div:

<div id="div1">div one</div>
<div id="div2">div two</div>
<a href="#" class="abuttons" data-divid="div1">link</a>

<script>
$(document).ready(function(){
    $(".abuttons").click(function () {
        var idname= $(this).data('divid');
        $("#"+idname).show("slow").siblings().hide("slow");
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

如果要使用类名而不是ID显示两个div,请将类名存储在achor标记上,在要显示的每个div上设置相同的类,并使用a .而不是jQuery在jQuery中引用它#

<div id="div1" class="divclass">div one</div>
<div id="div2" class="divclass">div two</div>

<a href="#" class="abuttons" data-divclass="divclass">link</a>

<script>
$(document).ready(function(){
    $(".abuttons").click(function () {
        var classname= $(this).data('divclass');
        $("."+classname).show("slow").siblings().hide("slow");
    });
});
</script> 
Run Code Online (Sandbox Code Playgroud)

  • 我想你会想要使用`data`属性来访问非标准的数据存储元素.http://api.jquery.com/data/ (2认同)