2016-04-02 21 views
0

Bu işlevleri daha genel olarak nasıl yazabilirim? Bu yüzden tekrar etmem gerekmiyor mu?Çoklu girişlerdeki benzer değişiklik olay işleyicisini basitleştirin

jQuery("input[name='option1']").change(function() { 
    $("#option1").addClass('highlight'); 
    setTimeout(function() { 
     $("#option1").removeClass("highlight"); 
    }, 100); 
}); 

jQuery("input[name='option2']").change(function() { 
    $("#option2").addClass('highlight'); 
    setTimeout(function() { 
     $("#option2").removeClass("highlight"); 
    }, 100); 
}); 

jQuery("input[name='optionX']").change(function() { 
    $("#optionX").addClass('highlight'); 
    setTimeout(function() { 
     $("#optionX").removeClass("highlight"); 
    }, 100); 
}); 
+0

misin onları elemanları DOM birbirleriyle ilgili olduğunu görebilirsiniz sorusuna HTML'nizi eklemenizi rica ediyorum. –

cevap

2

Sen, adı option ile başlayan tüm <input> unsurları olayı bağlamak için attribute starts with selector kullanabilirsiniz.

// Bind change event on all the `<input>` elements whose `name` attribute starts with `option`. 
$('input[name^="option"]').change(function() { 
    // Get the `name` of this element 
    var name = $(this).attr('name'), 
     elem = $('#' + name); // Get the corresponding element whose id is same as the name of this element 

    elem.addClass('highlight'); 
    setTimeout(function() { 
     // Use cached element object 
     elem.removeClass('highlight'); 
    }, 100); 
}); 
+1

Ne Giriş adı "seçenek" ile başlamıyorsa? –

+0

@AlexanderHein Lütfen söz konusu kodu kontrol edin, tüm eleman isimleri 'option' ile başlar. – Tushar

0

Bu deneyebilirsiniz:

//I would rather use a class instead of just input but anyhow... 
$('input').change(function(){ 
    var elem_name = $(this).attr('name'); 
    $('#'+elem_name).addClass('highlight'); 
    setTimeout(function() { 
     $('#'+elem_name).removeClass('highlight'); 
    }, 100); 
}); 
İlgili konular