在链接上返回false单击jquery
我希望有一个链接,点击时打开弹出窗口,但是如果用户没有启用JS,我希望它在新窗口中打开一个页面。
以下似乎不起作用,
terms and conditions function popUp(URL) { day = new Date(); id = day.getTime(); eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=600,left = 445,top = 150');"); } $('tac-link').click(function() { popUp('https://stackoverflow.com/questions/2058038/returning-false-on-link-click-jquery/tac.html'); return false; });
为了使此function更兼容浏览器,您需要将事件对象传递给click
处理程序,然后调用e.preventDefault();
。
例:
$( '#button' ).click( function( e ) { //... your code... e.preventDefault(); return false; } );
我认为你只是错误的id选择器。 尝试将$('tac-link')
更改$('#tac-link')
。
另一种方法:
$('a[target="_blank"]').click(function(e) { window.open( this.href ); e.preventDefault(); });
另请注意, event.preventDefault
并不存在于所有浏览器中,并且会导致IE7之类的错误(如果内存服务。)为避免这种情况,请使用常规if语句:
if (e.preventDefault) { e.preventDefault(); } e.returnValue = false;
这样可以防止抛出错误。 我相信jQuery也使用这种方法。
你只是错过了#表示它是一个id而不是一个节点名。
$('#tac-link')
PS – 我不建议使用eval
,为什么不将所有页面变量存储在对象中?
var pages = {}; function popUp( url ) { var id = +new Date; pages[id] = window.open( url ); }