非常简单的jQuery可重用函数问题
非常快速的jQuery问题 我有这个功能:非常简单的jQuery可重用函数问题,jquery,function,Jquery,Function,非常快速的jQuery问题 我有这个功能: $(document).ready(function() { $('a#show1').click(function() { $('.item1').toggle(1000); return false; }); $('a#show2').click(function() { $('.item2').toggle(1000); return false; }); // And it goes o
$(document).ready(function() {
$('a#show1').click(function() {
$('.item1').toggle(1000);
return false;
});
$('a#show2').click(function() {
$('.item2').toggle(1000);
return false;
});
// And it goes on...
});
脚本运行的页面上有任意数量的show和item div,它们都是唯一的,并标识为itemX
如何重写show1和show2的重复和相同的函数,使其基本上如下所示:
$('a#showX').click(function() {
$('.itemX').toggle(1000);
return false;
});
如果您知道有多少个,您可以使用for循环并附加变量
for(var i=1;i<=whatever;i++)
{
$('a#show' + i).click(function() { // ... etc ... // });
}
如果您知道有多少个,您可以使用for循环并附加变量
for(var i=1;i<=whatever;i++)
{
$('a#show' + i).click(function() { // ... etc ... // });
}
这是一个想法:
$('a#show1', 'a#show2').click(function() {
id = ".item" + this.id.substr(4);
$(id).toggle(1000);
return false;
});
这是一个想法:
$('a#show1', 'a#show2').click(function() {
id = ".item" + this.id.substr(4);
$(id).toggle(1000);
return false;
});
我希望它能工作,我没有测试它
$('a[id^=show]').click(function() {
var id = $(this).attr('id');
id = id.substring(id.length-1);
$('.item'+id).toggle(1000);
return false;
});
我希望它能工作,我没有测试它。我通常会尝试将项目保持在DOM中一致的相对位置:
$('a[id^=show]').click(function() {
var id = $(this).attr('id');
id = id.substring(id.length-1);
$('.item'+id).toggle(1000);
return false;
});
//all <a> with class .show-extra
$('a.show-extra').click(function() {
//get the next element with the class .show-extra-panel
$(this).next('.show-extra-panel').toggle(1000);
return false;
});
这将使任何类似的工作:
<a href="#" class="format-link show-extra">text</a>
<div class="info-panel show-extra-panel">extra toggle text</div>
我通常尝试将项目保持在DOM中一致的相对位置:
//all <a> with class .show-extra
$('a.show-extra').click(function() {
//get the next element with the class .show-extra-panel
$(this).next('.show-extra-panel').toggle(1000);
return false;
});
这将使任何类似的工作:
<a href="#" class="format-link show-extra">text</a>
<div class="info-panel show-extra-panel">extra toggle text</div>
@usoban的方法是正确的——第一个选择器中的“start with”语法将找到所有的“show”项,不管有多少项。您只需要调整代码,使其只提取“id”的数字部分,而不是全部提取,否则它将查找类为“.itemshow1”而不是“.item1”的元素
$("a[id^=show]").click(function(){
$(".item" + this.attr("id").substr(4)).toggle(1000);
});
EDIT@Keith也有一个很好的方法-使用类标记“show”元素-这样就不需要标识符的数字部分-然后依靠“item”的相对位置来定位它。@usoban有一个正确的方法-第一个选择器中的“start with”语法将查找所有“show”项,不管有多少。您只需要调整代码,使其只提取“id”的数字部分,而不是全部提取,否则它将查找类为“.itemshow1”而不是“.item1”的元素
$("a[id^=show]").click(function(){
$(".item" + this.attr("id").substr(4)).toggle(1000);
});
EDIT@Keith也有一个很好的方法——使用类来标记“show”元素——这样就不需要标识符的数字部分——然后依靠“item”的相对位置来定位它。啊,让我来试试吧,尽管在你的情况下id是。itemshow1你可能需要这样做:$.item+$this.attrid.toggle1000;那太完美了。我所要做的就是加上return false;直到最后,这样它就不会闪烁。谢谢啊,尽管在你的情况下id是。itemshow1你可能需要这样做:$.item+this.attrid.toggle1000;那太完美了。我所要做的就是加上return false;直到最后,这样它就不会闪烁。谢谢不错的方法,但当数字超过9时会中断:不错的方法,但当数字超过9时会中断: