2015-04-07 46 views
0

我正在使用帶有嵌套div的bootstrap MODAL插件(http://getbootstrap.com/javascript/#modals)。單擊內部div時,我想要顯示EDIT表單,單擊容器div時,我想顯示ADD NEW表單。請參閱下面的代碼。使用bootstrap模式的嵌套可點擊div

<div id="container" style="width:300px;height:300px;border-style:double;cursor:pointer;" data-target="#add" data-toggle="modal"> 
    <div id="inside" data-target="#edit" data-toggle="modal" style="width:180px; height: 180px; background-color: Aqua; cursor: pointer;"> 
     click here to edit 
    </div> 
    click outside to add 
</div> 

<!-- Modal for edit --> 
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
    <div class="modal-dialog"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
     <h4 class="modal-title" id="myModalLabel">EDIT</h4> 
     </div> 
     <div class="modal-body"> 
     (form for edit) 
     </div> 
     <div class="modal-footer"> 
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
     <button type="button" class="btn btn-primary">UPDATE</button> 
     </div> 
    </div> 
    </div> 
</div> 

<!-- Modal for add --> 
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
    <div class="modal-dialog"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
     <h4 class="modal-title" id="myModalLabel">ADD NEW</h4> 
     </div> 
     <div class="modal-body"> 
     (form for add new) 
     </div> 
     <div class="modal-footer"> 
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
     <button type="button" class="btn btn-primary">ADD</button> 
     </div> 
    </div> 
    </div> 
</div> 

問題是,單擊內部div時,編輯窗體和添加新窗體都會彈出。如果在內部div中添加onclick="event.stopPropagation();",它會停止彈出這兩個表單。

+0

你可以做小提琴嗎? –

回答

0

我已經想出了一個解決方案

$("#inside").click(function(){ 
     $("#inside").parent().addClass("no_click"); 
    }); 

    $("#container").click(function(event){ 
     if($(this).hasClass("no_click")){ 
      $(this).attr("data-toggle",""); 
      $(this).removeClass("no_click"); 
      return; 
     } 
     else{ 
      $(this).attr("data-toggle","modal"); 
     } 
    }); 

的想法是來自於這個帖子Preventing click event with jQuery drag and drop。那篇文章和我的問題都是關於一個動作觸發兩個事件的問題。

+0

實際上有一個更簡單的解決方案,而不是通過HTML屬性激活模態,也可以通過JavaScript(http://getbootstrap.com/javascript/#modals-usage)激活模態。然後'onclick =「event.stopPropagation();」'應該可以正常工作。 – Jun