2017-10-18 207 views
0

我需要確認用戶何時嘗試退出表單並單擊菜單;我嘗試使用preventDefault方法及其工作,但我需要在確認響應爲真後,獲取用戶單擊的菜單項的href設置。 我有這樣的HTML代碼:我怎樣才能獲得點擊鏈接href?

<ul class="page-sidebar-menu page-header-fixed page-sidebar-menu-hover-submenu "> 
     <li class="start "> 
       <a href="/Dashboard"> 
        <i class="icon-home"></i> 
        <span class="title">Dashboard</span> 
       </a> 
     </li> 
     <li class=" "> 
       <a href="javascript:;" class="auto"> 
        <i class="icon-wrench"></i> 
        <span class="title">Administration</span> 
       </a> 
       <ul class="sub-menu"> 
         <li> 
           <a href="/OrganizationUnits"> 
            <span><i class="sub-menu-icon icon-layers"></i> Organization units</span> 
           </a> 
         </li> 
       </ul> 
     </li> 
     <li class=" "> 
       <a href="javascript:;" class="auto"> 
       <a href="javascript:;" class="auto"> 
        <span class="title">Base Info</span> 
       </a> 
       <ul class="sub-menu"> 
         <li> 
           <a href="javascript:;" class="auto"> 
            <i class="fa fa-map-marker"></i> 
            <span class="title">Area</span> 
            <span class="arrow"></span> 
           </a> 
           <ul class="sub-menu"> 
             <li> 
              <a href="/Country"> 
               <span><i class="sub-menu-icon fa fa-map-marker"></i> Countries</span> 
              </a> 
             </li> 
             <li> 
              <a href="/Zone"> 
               <span><i class="sub-menu-icon fa fa-map-marker"></i> Zones</span> 
              </a> 
             </li> 
           </ul> 
         </li> 
       </ul> 
     </li> 
</ul> 

我試圖找到鏈接的href後各個環節的點擊。以下代碼是我的java腳本:

$('ul.page-sidebar-menu li a').click(function(e) { 
    e.preventDefault(); 
    confirm("Are You Sure To Exit From This Form?", function (isConfirm) { 
     if (isConfirm) { 
      window.location = $(this).attr('href'); 
     } 
    }); 
}); 

但是$(this).attr('href')等於undefined。 如何獲得點擊鏈接href?

+0

嘗試此代替 - 如果(event.target.tagName.toLowerCase()=== 'A') { event.target.href; //這是錨標記指向的網址。 } –

回答

1

裏面confirm的回調處理程序的this範圍改變局部的功能,

所以將其更改爲

$('ul.page-sidebar-menu li a').click(function(e) { 
    e.preventDefault(); 
    var $self = $(this); //notice this new line 
    confirm("Are You Sure To Exit From This Form?", function (isConfirm) { 
     if (isConfirm) { 
      window.location = $self.attr('href'); //notice $(this) is replaced by $self 
     } 
    }); 
}); 
1

添加到gurvinder372的答案,你也可以用箭頭的功能,而不是將this分配給$self

$('ul.page-sidebar-menu li a').click(function(e) { 
    e.preventDefault(); 
    confirm("Are You Sure To Exit From This Form?", isConfirm => { 
     if (isConfirm) { 
      window.location = $(this).attr('href'); 
     } 
    }); 
});