gpt4 book ai didi

javascript - 我怎样才能获得点击的链接href?

转载 作者:行者123 更新时间:2023-12-01 02:54:17 25 4
gpt4 key购买 nike

当用户尝试退出表单并单击菜单时,我需要确认用户;我尝试使用 PreventDefault 方法及其工作,但我需要获取用户在确认响应为 true 后单击它进行设置的菜单项的 href。我有这个 HTML 代码:

<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')等于未定义。如何获得点击的链接href?

最佳答案

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
}
});
});

关于javascript - 我怎样才能获得点击的链接href?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46803836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com