JavaScript重定向和window.open

One of the sweet parts in the simplified HTML5 spec was allowing A elements to wrap DIVs and other block level elements.  For too long we added JavaScript listeners and window.location redirects when a wrapping A would have probably sufficed.  But there are also times when the wrapping A wouldn't work -- for example, a block with A elements already within it -- you just want clicks on anything else within the parent to land at a given location.

简化HTML5规范中最甜蜜的部分之一是允许A元素包装DIV和其他块级元素。 很长时间以来,当包装A可能已足够时,我们添加了JavaScript侦听器和window.location重定向。 但是有时候,包装A不能正常工作-例如,其中已经包含A元素的块-您只希望单击父对象中的任何其他对象以将其放在指定位置。

Of course a basic listener like this would work:

当然,像这样的基本侦听器将起作用:


someElement.addEventListener('click', function(e) {
	// not important what the URL is but assume it's available on
	// the element in a `data-src` attribute
	window.location = someElement.get('data-url');
});


...but it would succumb to one of my biggest pet peeves:  COMMAND+CLICK'ing a block and the link opening in the same window.  The closer we can get custom-coded blocks to native browser functionality the better.  So take a moment and fix your event listener callbacks:

...但是它会屈服于我最大的烦恼之一: COMMAND+CLICK '阻止一个块,并且链接在同一窗口中打开。 我们越接近获得自定义编码的块来获得本机浏览器功能越好。 因此,花点时间修复您的事件监听器回调:


someElement.addEventListener('click', function(e) {
	var url = someElement.get('data-url');

	if(e.metaKey || e.ctrlKey || e.button === 1) {
		window.open(url);
	}
	else {
		window.location = url;
	}
});


I've implemented this on my blog and it's something I keep in mind whenever I use a window.location redirect.  It's a minimal code addition but a major usability boost!

我已经在博客上实现了这一点,每当我使用window.location重定向时,我都会记住这一点。 这是最少的代码添加,但大大提高了可用性!

翻译自: https://davidwalsh.name/window-open

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值