为什么这段代码在IE6或IE7中不起作用?
$('a').click(
function()
{
var urlIsExternal = true;
var urlMedicareDir = '/medicare/';
var urlMedicareHost = 'health.healthcare.com';
var urlMedicare = 'https://' + urlMedicareHost + urlMedicareDir;
var urlAppsHost = 'apps.healthcare.com';
var urlCurrent = String( window.location );
var urlCurrentPrefix = urlCurrent.substring( 0, urlMedicare.length );
var urlCurrentURL = $.url( urlCurrent );
var urlClicked = $(this).attr('href');
var urlClickedURL = $.url( $(this).attr('href') );
var urlHost = urlClickedURL.attr('host');
if( !urlHost.length )
{
urlHost = urlCurrentURL.attr('host');
}
var urlConfirmMessage = 'You are now leaving the Medicare website.';
if( urlCurrentPrefix == urlMedicare )
{
if( urlClicked.substring( 0, 1 ) == '/' ) // starts with slash
{
if( urlClicked.substring( 0, urlMedicareDir.length ) == urlMedicareDir )
{
urlIsExternal = false;
}
}
if( urlClicked.substring( 0, urlMedicare.length ) == urlMedicare )
{
urlIsExternal = false;
}
if (
urlClicked.substring( 0, 1 ) != '/' &&
urlClicked.substring( 0, 4 ) != 'http' &&
urlClicked.substring( 0, 4 ) != 'file'
)
{
urlIsExternal = false;
}
if( urlAppsHost == urlHost )
{
urlIsExternal = false;
}
if( urlClicked.substring(urlClicked.length-4) == '.pdf' )
{
urlIsExternal = false;
}
}
else
{
urlIsExternal = false;
}
if( urlIsExternal )
{
if( confirm( urlConfirmMessage ) )
{
window.open( urlClicked );
return false;
}
else
{
return false;
}
}
else
{
return true;
}
}
);
出于某种原因,在IE6或IE7中单击链接时,它们不会将用户定向到链接,也不会提示确认对话框。它应该提示确认对话框,但由于某种原因,它不是。
答案 0 :(得分:1)
我不认为您正在阻止锚点的默认操作(" a")。
你应该开始$('a').click( function( event ) {
,以便当你到达时:
if( urlIsExternal ) {
// This tells jQuery to NOT follow the hyperlink
event.preventDefault();
if( confirm( urlConfirmMessage ) ) {
window.open( urlClicked );
}
}
但是,真正缺少的是此代码需要在 文档加载后运行 。所以你只需要用
包装你的函数$(document).ready(function(){
$('a').click( function( event ) {
/* your code */
}
});
如果没有调用$(document).ready()
,JavaScript会在文档正文呈现之前运行,因此它无法找到任何可以附加点击事件的<a>
标记。< / p>
答案 1 :(得分:1)
似乎如果用户点击的链接的href以当前主机以外的某个值开头,则需要提供确认对话框。这是一个真正令人讨厌的策略,为什么用户不知道之前点击它会将其带到别处的链接?
无论如何,你想要做的简单版本是:
function showPrompt() {
return confirm('Do you really want to leaving ' + window.location.host +
'?\nPress OK to continue or Cancel to stay on this page.');
}
window.onload = function() {
// The links collection is live and available as a property of window
var link, links = document.links;
// Include criteria for host, hostName, protocol, whatever as required
var re = new RegExp(window.location.host || 'no host');
for (var i=0, iLen=links.length; i<iLen; i++) {
link = links[i];
// Only add the listener to links that need it
if (!re.test(link.href)) {
// Add the listener however you want, this way is simple and robust
link.onclick = showPrompt;
}
}
}