繁体   English   中英

如何知道哪个div在类中调用了函数?

[英]How to know which div called a function in a class?

我有六个用作按钮的div。 单击时,将显示不同div(和类)中的一个跨度,而其他的则被隐藏。

纽扣:

<div class="menu">
    <div class="menubutton">
        Menu1
    </div>
      .
      .
      .
    <div class="menubutton">
        Menu6
    </div>
</div>

根据点击的按钮显示的信息:

<div class="information">
    <span class="information1"> Info1 </span>
    ...
    <span class="information6"> Info6 </span>
</div>

我如何知道哪个调用了该函数,以便知道哪个范围可见?

只要您的标记是这种方式:

<div class="menu">
    <div class="menubutton">
        Menu1
    </div>
     <div class="menubutton">
        Menu2
    </div>
     <div class="menubutton">
        Menu3
    </div>
     <div class="menubutton">
        Menu4
    </div>
     <div class="menubutton">
        Menu5
    </div>
    <div class="menubutton">
        Menu6
    </div>
</div>
<div class="information">
    <span class="information1"> information1 </span>
    <span class="information2"> information2 </span>
    <span class="information3"> information3 </span>
    <span class="information4"> information4 </span>
    <span class="information5"> information5 </span>
    <span class="information6"> information6 </span>
</div>

你可以这样做:

$('.menubutton').click(function(){
     var index = $('.menubutton').index(this); //get the index of the menubutton clicked
    $('.information > span').eq(index).show().siblings().hide(); // show the corresponding information item based onthe clicked one's index and hide others.
});

演示版

这样,您可以安全地删除带有索引的类,例如information1, information2等,而可以添加一个通用类,如content

 <div class="information">
        <span class="content"> information1 </span>
        <span class="content"> information2 </span>
        <span class="content"> information3 </span>
        <span class="content"> information4 </span>
        <span class="content"> information5 </span>
        <span class="content"> information6 </span>
    </div>

并将其更改为:

$('.menubutton').click(function(){
         var index = $('.menubutton').index(this); //get the index of the menubutton clicked
        $('.information > .content').eq(index).show().siblings().hide(); // show the corresponding information item based onthe clicked one's index and hide others.
    });

由于您没有ID,我们可以获取所单击菜单项的索引,将其加1,然后找到相应的information范围以显示:

$(".menubutton").click(function() {
    var menuIndex = $(this).index() + 1;
    $(".information" + menuIndex).show();
});

函数内部的this关键字引用调用该函数的元素。

添加#id每个menubutton ,那么:

<div class="menubutton" id="btn_1"></div>

然后:

$(".menubutton").on("click", function() {
  // Get the id of button clicked.
  var id = $(this).attr("id").split("_")[1];

  // Target SPAN with the same id.
  $("SPAN.information" + id).show();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM