2013-03-05 251 views
0

有沒有辦法縮短這個感覺就像我在重複代碼,看起來很不整潔?重複的代碼

jQuery(document).ready(function() { 
    $('.allText').hide(); 


$('#b1').click(function() { 
    $('.allText').hide(); 
    $('#text1').fadeIn(800); 
}); 

$('#b2').click(function() { 
    $('.allText').hide(); 
    $('#text2').fadeIn(800); 
}); 

$('#b3').click(function() { 
    $('.allText').hide(); 
    $('#text3').fadeIn(800); 
}); 

$('#b4').click(function() { 
    $('.allText').hide(); 
    $('#text4').fadeIn(800); 
}); 

$('#b5').click(function() { 
    $('.allText').hide(); 
    $('#text5').fadeIn(800); 
}); 

$('#b6').click(function() { 
    $('.allText').hide(); 
    $('#text6').fadeIn(800); 
}); 


$('#b7').click(function() { 
    $('.allText').hide(); 
    $('#text7').fadeIn(800); 
}); 

}); 
+0

你能分享相應的標記? – aletrasg 2013-03-05 15:45:05

回答

3
$('#b1,#b2,#b3,#b4,#b5,#b6').click(function() { 
    $('.allText').hide(); 
    $('#text'+this.id.substr(-1)).fadeIn(800); 
}); 
1

創建一個接受數作爲參數的新的功能,然後添加字符串一起:

$('#b' + id).click(function() { 
    $('.allText').hide(); 
    $('#text' + id).fadeIn(800); 
}); 

在這種情況下id是參數。

然後,您可以創建一個for循環來反覆運行該函數。在需要添加東西的情況下,這非常容易。

1

你可以指定一個類,使一些後像這樣(如果你把你的元素類 「bclass」)

$('.bclass').click(function(){ 
    $('.allText').hide(); 
    $('#text'+this.id.substr(-1)).fadeIn(800); 
}); 
2

添加class到B爲例元素:

<div id="b1" class="b"></div> 
<div id="b2" class="b"></div> 
<div id="b3" class="b"></div> 

並使用class點擊事件

$('.b').click(function() { 
    $('.allText').hide(); 
    $('#text'+this.id.substr(-1)).fadeIn(800); 
}); 

OR

<div id="b1" class="b" data-text="#text1"></div> 
<div id="b2" class="b" data-text="#text2"></div> 
<div id="b3" class="b" data-text="#text3"></div> 


$('.b').click(function() { 
    $('.allText').hide(); 
    $((this).data("text")).fadeIn(800); 
}); 

AS @joeframbach建議您可以重構這個

+0

或甚至

和$($(this).data('ref'))。fadeIn(800); – 2013-03-05 15:55:57

+0

我付了它,數據是HTML5屬性。而且它更優雅... – 2013-03-05 15:57:19

0

一種方式是通過將人的B#元素div標籤,然後選擇div標籤與它的ID /類,並使用.children()得到所有的b#元素。

例子:

$('#mydiv').children().click(function() { 
    $('.allText').hide(); 
    $('#text2').fadeIn(800); 
});