我在StackOverflow中搜索了我认为是一个基本问题的内容,但是找不到任何相关的线程。主要是因为我觉得我在寻找错误的关键字。
我想知道如何将下一段总结成尽可能少的代码行。当您单击'link-#‘时,它会从隐藏的div’more -#中加载内容(其中# in more可以是任意数字,但与link-#中的数字相同)。现在我有一个:
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)
});我敢打赌你们一定知道怎么处理这事!谢谢你的帮助。
诚挚的问候,
托马斯
发布于 2015-03-13 18:56:03
给他们所有相同的类名,然后添加属性"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>发布于 2015-03-13 18:57:23
一种更好的方法是通过给这些项提供相同的类来对它们进行分组,并使用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>
https://stackoverflow.com/questions/29039830
复制相似问题