如何重构在不同DIV上运行的模态为DRY?

时间:2015-07-17 14:04:21

标签: javascript jquery

我的页面上有大约9个小的javascript函数,它们都做同样的事情,为按钮所在的div内的内容打开一个模态。

它们之间的唯一区别是每个都引用了不同的div。我想重构这段代码,这样我就不会重复任何执行模态操作的代码了。

Here is the codepen

使用Javascript:

// FINDS THE MODAL AND THEN PLACES THE IBOX CONTENT THAT IS CURRENTLY
// ACTIVE INSIDE THE MODAL'S BODY

$('[data-target="#enlargeElementModal"]').on('click', function () {
    $('#enlargeElementModal .modal-body').html($('#ibox-1 .content.active').html());
});

$('[data-target="#enlargeStrategyModal"]').on('click', function () {
    $('#enlargeStrategyModal .modal-body').html($('#ibox-2 .content.active').html());
});

....and many more of these

一些HTML:

// IMPORTANT PART OF ENLARGE MODAL
<div class="modal modal-wide fade" id="enlargeElementModal" role="dialog"><!--ENLARGE SCREEN MODAL-->
      <div class="modal-dialog">
             <div class="modal-content">
                     <div class="modal-header">
                           <button type="button" class="close" data-dismiss="modal">
                           <span class="glyphicon glyphicon-remove"></span>
                           </button>
                           <h4 class="modal-title">Element Map</h4>
                     </div>
             <div class="modal-body">
                  <p></p>
             </div>
             <div class="modal-footer">
                   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
             </div>
        </div>
   </div>
</div>


// IMPORTANT PART OF IBOX-CONTENT
<div class="ibox-content mapStyle" id="ibox-1"><!--CONTENT INSIDE THE DIV BODY-->
                <div class="active content" id="elementMap"><!--MAP CONTENT-->
                ....content
                </div>
</div>

如何重构模态JavaScript以便我不重复代码?

1 个答案:

答案 0 :(得分:2)

我会在每个按钮上添加另一个data-*属性,以指示内容的来源:

<button type="button" class="btn btn-default btn-xs" data-toggle="modal"
     data-target="#enlargeStrategyModal" data-content="#ibox-2">

然后使用相同的代码激活每个按钮:

$('[data-target]').on('click',function(){
    var target = $(this).data('target');
    var content = $(this).data('content');
    $(target + ' .modal-body').html($(content + ' .content.active').html());
  });

实例:http://codepen.io/anon/pen/dojRRZ