繁体   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