2017-09-01 46 views
0

我是JavaScript新手。如果只有孩子存在,我想要顯示sweetalert。我有一個容器,如果我添加了一些東西,並嘗試導航到其他頁面而不保存,那麼sweetalert應彈出並詢問是否保存或離開。如何添加sweetalert取決於孩子是否存在

許多迭代後我的代碼是

jQuery(document).click(function(e) { 
    if(document.getElementById($scope.mainContainerId).children().length>0) { 
     if (jQuery(e.target).is('a')) { 
      e.preventDefault(); 

       swal({ 
        title: "Are you sure?", 
        text: "Want to continue without saving?", 
        type: "warning", 
        showCancelButton: true, 
        confirmButtonColor: "#DD6B55", 
        confirmButtonText: "Leave", 
        closeOnConfirm: false, 
        html: false 
       }, 

       function(isConfirm) { 
        if (isConfirm) { 
         window.location = jQuery(e.target).attr('href'); 
        } 
       }); 
      } 


    }; 
}); 

回答

0

<element>.children不是一個功能,因此添加括號應該拋出一個錯誤。因此,如果條件不會被評估爲真,

if(document.getElementById($scope.mainContainerId).children().length>0) {} 

要解決這個問題,您應該能夠在children之後簡單地刪除括號。

jQuery(document).click(function(e) { 
    if(document.getElementById($scope.mainContainerId).children.length>0) { 
    if (jQuery(e.target).is('a')) { 
     e.preventDefault(); 

     swal({ 
     title: "Are you sure?", 
     text: "Want to continue without saving?", 
     type: "warning", 
     showCancelButton: true, 
     confirmButtonColor: "#DD6B55", 
     confirmButtonText: "Leave", 
     closeOnConfirm: false, 
     html: false 
     }, 
     function(isConfirm) { 
      if (isConfirm) { 
      window.location = jQuery(e.target).attr('href'); 
      } 
     }); 
    } 
    } 
});