当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Repeating of code

问题描述:

Is there a way to shorten this it feels like i am repeating code, and looks very untidy?

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);

});

});

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

add class to b elements for example:

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

and use class to click event

$('.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 suggestion

网友答案:

Create a new function that accepts a number as a parameter, then add the strings together:

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

In this case id is the parameter.

Afterwards you can create a for loop to run that function over and over again. In the condition where you need to add something, this pretty much makes your life easy.

网友答案:

you can assign a class and after make something like this (if you put into your element class "bclass")

$('.bclass').click(function(){
    $('.allText').hide();
    $('#text'+this.id.substr(-1)).fadeIn(800);
});
网友答案:

One way you can refactor this is by putting al the b# elements in a div tag and then select that div tag with it's id/class and use .children() to get all the b# elements.

Example:

$('#mydiv').children().click(function() {
    $('.allText').hide();
    $('#text2').fadeIn(800);
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: