将多个类似功能合二为一

时间:2015-03-13 18:51:51

标签: javascript arrays

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

我想知道如何将下一位总结为尽可能少的代码行。当你点击'link-#'时,它会加载来自隐藏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)
});

我打赌你们知道如何处理这件事!谢谢你的帮助。

致以最诚挚的问候,

托马斯

2 个答案:

答案 0 :(得分:2)

一种更好的方法是通过为这些项提供相同的类来对这些项进行分组,并使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

为它们提供所有相同的类名,然后添加属性“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>
相关问题