2017-09-01 47 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'); 
      } 
     }); 
    } 
    } 
});