重复功能

Ma9*_*9ic 3 jquery

在编写简单的东西时,我似乎重复了很多函数,有没有更好的方法呢?

  $('#bt1').click(function() {
      $('#txt1').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 

  $('#bt2').click(function() {
      $('#txt2').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 

  $('#bt3').click(function() {
      $('#txt3').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 

  $('#bt4').click(function() {
      $('#txt4').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 
Run Code Online (Sandbox Code Playgroud)

所以我不重复代码?

bil*_*can 6

给你的按钮class,例如btn,然后你可以这样做: -

$('.btn').click(function() {
  $('#' + this.id.replace('bt', 'txt')).show();
  $(this).css("background-image", "url(site_images/08/btn_over.png)"); 
});
Run Code Online (Sandbox Code Playgroud)