将多个相似的功能合二为一

Combining multiple similar functions into one

本文关键字:功能 合二为一 相似      更新时间:2023-09-26

我已经在StackOverflow中搜索了我认为的基本问题,但我找不到任何相关的线程。主要是因为我觉得我搜索了错误的关键字。

我想知道如何将下一点总结为尽可能少的代码行。当您单击"链接-#"时,它会从隐藏的div"more-#"加载内容(其中更多中的#可以是任何数字,但与链接-#中的数字相同。现在我有这个:

jQuery("#link-1").click(function(){
    jQuery('#more').hide().html($('#more-1').html()).fadeIn(400)
});
jQuery("#link-2").click(function(){
    jQuery('#more').hide().html($('#more-2').html()).fadeIn(400)
});
jQuery("#link-3").click(function(){
    jQuery('#more').hide().html($('#more-3').html()).fadeIn(400)
});

等。

我认为它应该是如下所示的,但显然这不是正确的方法。

jQuery("#link" + NUMBER ).click(function(){
    jQuery('#more').hide().html($('#more-' + this.NUMBER).html()).fadeIn(400)
});

我敢打赌你们确切地知道如何处理这个问题!谢谢你的帮助。

此致敬意

托马斯

一种可取的方法是通过为这些项提供相同的类来对这些项进行分组,并使用 data-* 属性来标识关联的元素:

jQuery(function() {
  jQuery(".show-more").click(function() {
    var target = $(this).data('target');
    jQuery('#more').hide().html($(target).html()).fadeIn(400);
  });
});
#moreItems {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<a href="#" class="show-more" data-target="#more-1">Show More 1</a>
<a href="#" class="show-more" data-target="#more-2">Show More 2</a>
<a href="#" class="show-more" data-target="#more-3">Show More 3</a>
<div id="more"></div>
<div id="moreItems">
  <div id="more-1">Here are the details 1</div>
  <div id="more-2">Here are the details 2</div>
  <div id="more-3">Here are the details 3</div>
</div>

给它们相同的类名,然后添加属性"data-num",然后:

jQuery(".className").click(function () {
    var $this = $(this);
    var html = jQuery('#more' + $this.attr('data-num')).html();
    jQuery('#more').hide().html(html);
});

示例 HTML:

<a class='className' data-num='1'>Link</a>
<div id='more1'></div>
<div id='more'></div>