jQuery整合和清理

时间:2013-03-11 18:09:36

标签: jquery

写一个更清洁版本的最佳方法是什么。我有一些想法,但在这里会有第二意见。

$('.screenshot1').click(function(){
    $('#screenshot1').show();
});
$('.screenshot2').click(function(){
  $('#screenshot2').show();
});
$('.screenshot3').click(function(){
  $('#screenshot3').show();   
});
$('.screenshot4').click(function(){
  $('#screenshot4').show();
});
  $('.screenshot5').click(function(){
    $('#screenshot5').show();
  });
$('.screenshot6').click(function(){
  $('#screenshot6').show();   
});
$('.screenshot7').click(function(){
  $('#screenshot7').show();   
});
$('#screenshot1, #screenshot2, #screenshot3, #screenshot4, #screenshot5, #screenshot6, #screenshot7, .modal-backdrop').click(function() {
  $('#screenshot1').hide();
  $('#screenshot2').hide();
  $('#screenshot3').hide();
  $('#screenshot4').hide();
  $('#screenshot5').hide();
  $('#screenshot6').hide();
  $('#screenshot7').hide();
});

HTML看起来像这样:

<a class="screenshot1" href="#"></a>
<div id="screenshot1">
  <img src='homepage/screenshot1.jpg' alt='Screenshot 1' height='565' width='756' />
</div>

等...

谢谢!

5 个答案:

答案 0 :(得分:2)

$("[class^=screenshot]").click(function() {
      $('[id^="screenshot"]').hide();         
      var id = this.className.match(/screenshot(\d+)/)[1];
      $('#'+id).show()
}

答案 1 :(得分:1)

我会为所有屏幕截图ID使用单个选择器,然后使用each method。编辑:PSR的答案更好。

答案 2 :(得分:0)

我会做这样的事情:

HTML:

<div class="container">
    <div class="screenshot">
        <img src="image.png"/>
    </div>
</div>

将相同的类应用于所有屏幕截图:

$('.screenshot').click(function(){
    $(this).parent('.container'). find('.screenshot') .each(function () {
        $(this).hide();
    });
    $(this).show();
});

答案 3 :(得分:0)

不是100%确定这是否是您的意思,但我希望它有助于找到正确的方法:

'use strict';
$(document).ready(function(){
    $('[class^="screenshot"]').click(function(){
        // Hide them all
        $('[id^="screenshot"]').hide();

        // Show only the clicked one
        var id_name = $(this).attr('id');
        $('#' + id_name).show();
    });
});
祝你好运!

答案 4 :(得分:0)

您可以使用以下内容简化第一个代码块,

$(".screenshot1, .screenshot2, .screenshot3, .screenshot4, .screenshot5, .screenshot6, .screenshot7").click(function(){ 
       $("#" + $(this).attr("class")).show();
    });

DEMO