簡體   English   中英

如何為許多不同的 ID 值重用 function?

[英]How can I reuse a function for many different ID values?

這是我編寫的一個 jQuery 片段,用於在頁面上實現顯示/隱藏效果。 s1,s2,s3...是按鈕 div 的 ID。 其中將有大約 25 個。 單擊按鈕 s1 時,將隱藏 div q1 並顯示 div q2。

是否有一種簡潔的方法可以只編寫一個這樣的片段來一次涵蓋所有案例而不是 26 個?

$("#s1").click(function(e) {
         $("#q1").hide();
         $("#q2").show();
         });

$("#s2").click(function(e) {
          $("#q2").hide();
         $("#q3").show();
         });

 $("#s3").click(function(e) {
         $("#q3").hide();
         $("#q4").show();
         });
.
.
,
.
.
.
.
.
$("#s25").click(function(e) {
         $("#q25").hide();
         $("#q26").show();
         });

使用循環?

for (let i = 1; i <= 25; ++i) {
  $("#s" + i).click(function(e) {
     $("#q" + i).hide();
     $("#q" + (i + 1)).show();
  });
}

另外,小切線提示:如果您不打算使用參數“e”,則無需聲明它:)

這不是處理任務的好方法。 依賴身份證應該是最后的手段。 相反,在您的元素上放置一個共享的 class 並使用對 select 元素的 DOM 遍歷來切換。

<a class="my-trigger-element-class">...</a>
<div class="my-toggled-element-class">...</div>

<script>
$('.my-trigger-element-class').click(function() {
    // here I assume that the toggled element immediately follows the trigger
    // this may not be the case, so adjust accordingly
    let toggledEl = $(this).next('.my-toggled-element-class');

    // hide all elements that aren't the adjacent one
    $('.my-toggled-element').not(toggledEl).hide();

    // show just the adjacent one
    $(this).next('.my-toggled-element-class').toggle();
});
</script>

檢查幾乎所有 jQuery 手風琴腳本,以了解其實際效果。 他們都使用它的變體。

您可以給每個按鈕一個 class,並為具有該 class 的元素添加一個單擊事件偵聽器。 單擊按鈕時,您可以使用this.id.match(/\d+/g);獲取其 id 號 ,然后使用在其他選擇器中檢索到的數字:

$(".myClass").click(function() {
  const [n] = this.id.match(/\d+/g); // get number from the id
  $("#q"+n).hide();
  $("#q"+(+n+1)).show();
}

您可以做的一件事是在按鈕上使用data-xxx屬性來制作通用的隱藏/顯示按鈕。 一個例子可能是這樣的

HTML:

<button class="show-hide-button" data-show="#q2" data-hide="#q1">Click</button>

JS:

$(".show-hide-button").click( function(e) {
    $($(this).data('show')).show();
    $($(this).data('hide')).hide();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM