Improve user experience: Use window. location and window. open to solve the page Jump problem, window. location
Original article address: JavaScript Redirects and window. open
Original Article Date: January 1, August 27, 2014
Translated on: February 1, August 31, 2014
Translated by: Tie
(Translator's note: This article solves the problem of opening a new page with JS when pressing Ctrl)
In simplified HTML5 specifications
AThe tag contains multiple
DIVAnd/or other block-level elements.
<A>The tag contains block elements, so that JavaScript is used to listen to and call
Window. locationImplement the page Jump (redirect) function.
However
<A>This packaging form of labels is also difficult-for example, there are some <a> labels in a block element, in this case, we only want to jump to a given address when you click a part other than <a> in the parent.
Of course, using a simple listener as follows can also meet our needs:
SomeElement. addEventListener ('click', function (e) {// The URL address can be anything, or you can use other code to specify. // The 'data-src' DOM attribute window of the element is used here. location = someElement. get ('data-url ');});
... However, this sometimes has a bad user experience. When you press and hold the CTRL key (the Mac is the COMMAND key) and then click the mouse, it will open the link in the same (Tab) window. If you know this problem, you must have thought of how to solve it. We can achieve this goal by modifying a little bit of code. Please take the time to fix your listener:
SomeElement. addEventListener ('click', function (e) {// obtain URL var url = someElement. get ('data-url'); // determines whether the CTRL key is pressed if (e. metaKey | e. ctrlKey | e. button = 1) {window. open (url);} else {window. location = url ;}});
The original author has implemented this function on http://davidwalsh.name/website, in the use
Window. locationYou should also remember this when performing page redirection. This is a small code improvement, but it is very important to improve availability!
How can I get the environment on the previous page after I use windowlocationhref to jump to the page?
Window. location. href is used to retype an address in the address bar, rather than refreshing or redirecting, but opening a page.
In this way, the environment of the previous page cannot be obtained.
Windowlocation redirection
The toString method of the location object returns the href attribute, so location can be used instead of location. href.