簡體   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