Jquery Modal弹出重定向

问题描述 投票:0回答:3

我正在创建一个弹出窗口,当用户点击外部链接时会显示该弹出窗口。用户可以通过单击“确定”按钮继续选择。否则,如果用户点击“取消”,则用户停留在页面上。

我能够检测用户何时点击外部链接并使模式显示正常。

我在网上找到了一个关于如何使用Jquery创建模态实例的教程。在大多数情况下,我能够根据自己的喜好调整模态(尽管存在一些对齐问题)。

我遇到的问题是如何获取被点击到Jquery中创建的模态实例的锚标记的url。

我认为可行的一种方法是在Modal实例外创建按钮,当我在单击函数中调用Modal时打开这些按钮(下面显示我将变量设置为模式以在锚标记时打开单击)这也解决了我之前提到的对齐问题。

       var m = modal.open({content: "<div class='modal-content'><div class='modal-header'>
<h4 class='modal-title'>You are Now Leaving Our Site</h4>
<button id='closex' style='margin:5px' type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>x</span></button></div>
<div class='modal-body'>" 
+ "<p>You are now exiting the Regal Medical Group, Inc.  (RMG) web site.  When you exit this site to access a different non-RMG web site, you become subject to the other web site’s privacy policy and practices.  To learn about the other web site’s policy and practices, refer to the privacy policy statement posted on the web site’s home page.<br /><br />Press Ok to Continue<br />Press Cancel to Abort</p>" + "<br />" + "<div class='modal-footer'><button id='redirect' class='ok' href='#'>Ok</button><button id='close' class='cancel' href='#'>Cancel</button></div></div></div>"});

然后我想我可以创建函数来检查点击了哪些按钮。如果单击“确定”按钮,则捕获网址,清除叠加层,清除模式(原因是网站上的某些链接在锚标记中具有“target =”_ blank“)并将用户重定向到欲望的网站。否则,如果“取消”,清除叠加层,清除模态并保持在同一页面。

但是,这种方法不起作用。

我的问题:我怎样才能让这些按钮在Modal实例中工作?

以下是所有锚标记的点击函数(其中变量“m”是模态):

$( document ).ready(function() {



$('a').on('click', function(e){
        e.preventDefault();
        var url = $(this).attr('href'),
            host = location.host;

        console.log("URL: " + url + " HOST: " + host);

        if (url.indexOf(host) > -1 || url.indexOf('http','https') == -1){
            /* If we find the host name within the URL,
               OR if we do not find http or https, 
               meaning it is a relative internal link
            */
            window.location.href = url;
        } else {
var m = modal.open({content: "<div class='modal-content'><div class='modal-header'>
    <h4 class='modal-title'>You are Now Leaving Our Site</h4>
    <button id='closex' style='margin:5px' type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>x</span></button></div>
    <div class='modal-body'>" 
    + "<p>You are now exiting the Regal Medical Group, Inc.  (RMG) web site.  When you exit this site to access a different non-RMG web site, you become subject to the other web site’s privacy policy and practices.  To learn about the other web site’s policy and practices, refer to the privacy policy statement posted on the web site’s home page.<br /><br />Press Ok to Continue<br />Press Cancel to Abort</p>" + "<br />" + "<div class='modal-footer'><button id='redirect' class='ok' href='#'>Ok</button><button id='close' class='cancel' href='#'>Cancel</button></div></div></div>"});
if(m == true) {
                return m;
            } 
        }
        });

    });

以下代码是模态的实例:

/*Pop-Up Modal Set UP
========================================*/
var modal = (function(){
    var 
    method = {},
    $overlay,
    $modal,
    $content;/*,
    $close,
    $cancel,
    $ok;*/

    // Center the modal in the viewport
    method.center = function () {
        var top;
        var left;

        top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2;
        left = Math.max($(window).width() - $modal.outerWidth(), 0) / 2;

        $modal.css({
            top:top + $(window).scrollTop(), 
            left:left + $(window).scrollLeft()
        });
    };

    // Open the modal
    method.open = function (settings) {
        $content.empty().append(settings.content);

        $modal.css({
            width: settings.width || 'auto', 
            height: settings.height || 'auto'
        });

        method.center();
        $(window).bind('resize.modal', method.center);
        $modal.show();
        $overlay.show();
    };

    // Generate the HTML and add it to the Modal document
    $overlay = $('<div class="overlay" style="display: none;"></div>');
    $modal = $('<div class="modal id="myModal"></div>');
    $content = $('<div class="modal-dialog">');

    $modal.hide();
    $overlay.hide();
    $modal.append($content);

    $(document).ready(function(){
        //Add the Overlay and Modal
        $('body').append($overlay, $modal); 
    });

    return method;
}());
jquery html
3个回答
0
投票
  1. 返回后没有执行任何操作
  2. 你已经有了e.preventDefault();
  3. 不推荐使用.on的bind

回答:

存储URL并稍后使用

var $currentLink;
$('a').on('click', function(e){
    e.preventDefault();
    $currentLink = $(this); 


...

$(document).on("click","#redirect",function(e) {
  e.preventDefault();
  if ($currentLink) location = $currentLink.attr('href');
});

0
投票

在这里,您有一个我理解您需要的完整示例。正如您将注意到的,我不是每次都重新创建对话框,只是在不需要时隐藏它。您可能还会注意到async / await和数组表示法语法。如果您需要与旧版浏览器兼容,可以轻松转录或转换,但我希望您能更好地理解它。

        
        confirm = (url) => {
		return new Promise((resolve, reject) => {
			let yes = $('#overlay button#yes')
			let no = $('#overlay button#no')
			
			off = (then) => {
				yes.off() 
				no.off() 
				$('#overlay').addClass('hidden')
				then()
				}
				
			yes.one('click', () => {off(resolve)})
			no.one('click', () => {off(reject)})
		
			$('#overlay #link').text(url)
			$('#overlay').removeClass('hidden')
		})
	}
	
	jump = (url, target) => {
		if(!target || target == '_self') {
			window.location.href = url;
		} else {
			window.open(url, target)
		}
	}
	
	handle = async(e) => {
		e.preventDefault()
		link = e.currentTarget
		
		let url = $(link).attr('href')
		let target = $(link).attr('target')
        let host = location.host

        if ((host && url.indexOf(host) > -1) || !/^https?:/.test(url)){ // relative link
			jump(url, target)
		} else {
			try {
				await confirm(url)
				jump(url, target)
			} catch(e) {/*nope*/}
		}
	}
	
	attach = () => {
		$('#content').on('click','a', handle)
	}
	
	$(attach)
#overlay {
	position: absolute;
	top:0;
	left:0;
	right:0;
	bottom:0;
	background-color: rgba(0,0,0,.5);
	display: flex;
}

#confirm-dialog {
	position: relative;
	width: 50%;
	min-height: 7em;
	background-color: white;
	border: 1px solid black;
	border-radius: .5em;
	margin: auto auto;
}

#confirm-dialog h1 { 
	font-family: Verdana, Geneva, sans-serif; 
	font-size: 1.5rem; 
	font-style: normal; 
	font-variant: normal; 
	font-weight: 700; 
	line-height: 1.7rem; 
	text-align: center;
	}

#footer {
	position: absolute;
	height: 3em;
	bottom: 0;
	width: 100%;
	justify-content: flex-end;
	display: flex;
	border-top: 1px solid gray;
}
#link {
	margin-bottom: 3em;
	padding: .5em;
	text-align: center;
	font-size: 1.5em;
}
#footer button {
	width: 10em;
	margin: .2em 1em;
}

.hidden {
	display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="overlay" class="hidden">
	<div id="confirm-dialog">
		<h1>Do you want to navigate to:</h1>
		<div id="link"></div>
		<div id="footer">
			<button id="yes">Yes</button>
			<button id="no">No</button>
		</div>
	</div>
</div>

<div id="content">
	This is an <a href="/apple">internal link</a> while this one is <a href="http://www.google.com" target="_blank">external</a> like <a href="http://codeproject.com">this</a> too.
</div>

PS:window.open不在这里工作,因为它运行沙箱。


0
投票

我要感谢所有帮助我解决问题的人。当弹出窗口出现在屏幕上时,我能够通过将href传递给ok按钮来弄清楚。在按钮中,我在href:e.currentTarget.href中传递以下值。一旦我补充说,它就像一个魅力。

如果其他人想要使用它,这是完整的代码:

$( document ).ready(function() {

    $('a').on('click', function(e){
        e.preventDefault();
        var url = $(this).attr('href'),
            host = location.host;

        if (url.indexOf(host) > -1 || url.indexOf('http','https') == -1){
            /* If we find the host name within the URL,
               OR if we do not find http or https, 
               meaning it is a relative internal link
            */
            window.location.href = url;
        } else {

            var m = modal.open({content: "<div class='modal-content'><div class='modal-header'>
            <h4 class='modal-title'>You are Now Leaving Our Site.</h4>
            <button id='closex' style='margin:8px' type='button' class='close' data-dismiss='modal' aria-label='Close'>
            <span aria-hidden='true'>x</span></button></div><div class='modal-body'>" 
            + "<p>You are now exiting the NameOfSite web site.  When you exit this 
            site to access a different non-NameOfSite web site, you become subject to the other web site’s privacy 
            policy and practices.  To learn about the other web site’s policy and practices, refer to the privacy 
            policy statement posted on the web site’s home page.<br /><br />Press Ok to Continue
            <br />Press Cancel to Abort</p>" + "<br />" + "<div class='modal-footer'>
            <a id='redirect' class='btn btn-primary' href='" + e.currentTarget.href + "' target='_blank'>Ok</a>
            <button id='close' class='btn btn-default' href='#'>Cancel</button></div></div></div>"});

            if(m == true) {
                return m;
            } 
        }
    });

});
© www.soinside.com 2019 - 2024. All rights reserved.