gpt4 book ai didi

jquery - 如何使用 jQuery 获取点击时的 anchor href 值?

转载 作者:行者123 更新时间:2023-12-01 08:22:48 24 4
gpt4 key购买 nike

假设我有一个这样的 anchor :

<a onClick="return confirm('Sure?')" href="http://stackoverflow.com/">Click here</a>

当我点击“点击这里”时,我是否可以获得href“http://stackoverflow.com/”的值?请记住,我没有其他属性可以提供帮助,例如 id 或 name!

我正在覆盖确认功能,如果用户单击“确定”,我需要将用户重定向到 anchor 中提供的位置,如下所示:

window.confirm = function(msg) {
var targetUrl = jQuery(this).attr("href");
jQuery("#alert_box").dialog({
autoOpen: false,
show: "slide",
modal: true,
width: 400,
resizable:false,
title: '<img src="icons/confirm.png" /> Confirm!',
buttons: { "Cancel": function() {
jQuery(this).dialog("close");
},
"OK": function() {
//jQuery(this).dialog("close");
jQuery(location).attr('href', targetUrl);
}
}
});

jQuery("#alert_box").html(msg);
jQuery("#alert_box").dialog("open");
return false;
}

任何帮助将不胜感激!

最佳答案

要重定向用户,请使用:

window.location.href = targetUrl;

而不是:

jQuery(location).attr('href', targetUrl);

删除内联 JavaScript 也是一个好主意,例如:

<a class="confirm" href="http://www.example.com">..</a>

// script.js
$('a.confirm').click(function(e) {
e.preventDefault();
if (confirm('Are you sure?')) {
window.location.href = $(this).attr('href');
}
});

还有this在您的确认函数声明中未引用 <a>元素。您可能想使用类似的东西:

<a onclick="return confirm(this, 'Sure?')" href="...">...</a>

// script.js
function confirm(e, msg) {
var targetUrl = $(e).href('attr');
// ...
}

关于jquery - 如何使用 jQuery 获取点击时的 anchor href 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240137/

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