将多个相似的功能合二为一
Combining multiple similar functions into one
我已经在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>
相关文章:
- 添加文字和评论功能更新Div
- JavaScript打印功能使日历停止工作
- 每当您在选择器内移动鼠标时,悬停功能就会重复
- 如何防止网页加载后自动启动功能
- 除修剪外的其他功能
- 悬停功能触发器
- 使用angularjs向浏览器发送servlet响应(下载功能)
- 删除CKEditor工具栏按钮,但不删除功能
- 异步facebook功能
- 如何将chrome扩展功能移植到移动设备(特别是jquery和trello)
- jQuery滚动功能只工作一次
- Graphiti中是否有任何工具提示功能
- React redux初始化功能,无论状态变化如何
- 在哪里可以学习ECMAScript标准中尚未包含的JavaScript功能
- 正在获取select上的功能id
- Rhino打印功能
- 使用(navigator.geolocation)检测浏览器功能错误
- 主体单击删除功能上的输入框宽度
- 两个功能合二为一 - 计算和提交表单
- 将多个相似的功能合二为一