[英]External Link Notification - JavaScript or JQuery
我正在寻找一种设置它的方法,这样,当单击外部链接时,它会警告人们他们正在离开该网站。 最好使屏幕变暗,并在屏幕中间的框中显示一条消息,并可以单击“确定”或“取消”。
我尝试使用此代码:
$("a.external").click(function () {
alert("You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.");
});
并给每个链接一个外部类,但它似乎不起作用。 我不想使用它,因为这意味着客户端将必须记住添加我更喜欢自动的类。
我也尝试使用此代码执行此操作,但无济于事:
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
var x=window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
var val = false;
if (x)
val = true;
else
val = false;
return val;
});
我正在使用WordPress 3.8.1。
在此先感谢您提供的任何帮助。
您的过滤器逻辑应该正确,请尝试使用Confirm函数,并使用jQuery而不是$。
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are about to proceed to an external website."))
{
// if user clicks 'no' then dont proceed to link.
e.preventDefault();
};
});
我在您网站上的开发工具中进行了尝试,如果您使用jQuery,它似乎可以正常工作。 我认为您可能有一些与$引起冲突的插件。
尝试使用confirm
而不是警报,因为这将暂停并等待用户输入。 然后,您需要function(e){ e.preventDefault(); }
function(e){ e.preventDefault(); }
以防止执行默认的链接操作。
要仅识别外部链接,您可以执行以下操作:
var ignoreClick = false;
$(document).ready( function(){
$('input[type="submit"], input[type="image"], input[type="button"], button').click(function(e) {
ignoreClick = true;
});
$(document).click(function(e) {
if($(e.target).is('a'))
checkLink(e);
});
$('a').click(function(e) {
checkLink(e);
return true;
});
checkLink = function(e){
// bubble click up to anchor tag
tempTarget = e.target;
while (!$(tempTarget).is('a') && !!tempTarget.parentElement) {
tempTarget = tempTarget.parentElement;
}
if ($(tempTarget).is('a')){
if(!!tempTarget && $(tempTarget).is('a') &&
(tempTarget.hostname == "" || tempTarget.hostname == "#" || tempTarget.hostname == location.hostname)){
ignoreClick = true;
}
}
}
});
并抓住人们与您可能使用的消息beforeunload
和confirm
选项
$(window).bind("beforeunload", function (e) {
if (!ignoreClick){
if(!confirm("Leaving website message")) {
e.preventDefault();
}
}
});
对我来说效果很好。 我只是删除了不必要的变量,但是原始脚本运行良好。
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
return window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
});
编辑
在@ user1308743的代码行之后,似乎在cgmp.framework.min.js中召唤了jQuery.noConflict()
模式,该模式解除了jQuery的$()
函数的绑定。 因此,请对任何jQuery实现使用jQuery()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.