鍍金池/ 問答/C++  HTML/ location.href跳轉(zhuǎn)和給a標簽設(shè)置點擊事件有什么區(qū)別

location.href跳轉(zhuǎn)和給a標簽設(shè)置點擊事件有什么區(qū)別

我本來用的是window.location.href=url來跳轉(zhuǎn)都相關(guān)的頁面,但是在某些第三方app里,發(fā)現(xiàn)好像不管用了,看別人的代碼,他是先創(chuàng)建一個隱藏的a標簽,然后給這個a標簽一個click事件,執(zhí)行跳轉(zhuǎn):

var a = document.createElement("a");

a.setAttribute("href", aV);
a.style.display = "none";

var ev = document.createEvent('HTMLEvents');

ev.initEvent('click', false, true);
a.dispatchEvent(ev);

那么請問location.href跳轉(zhuǎn)和給a標簽設(shè)置點擊事件有什么區(qū)別呢?

回答
編輯回答
練命

Wherever possible, you should use <a href="foo.html"> over window.location.href, for a number of very good reasons.

If you have javascript disabled, none of the links would work.
Spiders, such as Google Bot, do not interpret javascript, and so they won't follow any of your links.
IT BREAKS THE INTERNET. No, really though - the World Wide Web is built on the very basis of discoverable linkages between pages. Hiding these linkages with non-standard .. err, links, goes against that very premise.
It makes for a bad user experience: a user expects that when they mouse over a link, they will have access to some information:
the destination displayed in the status bar (very important!)
right-click -> copy link location
middle-click -> open new tab
etc
Using window.location breaks all of these
It's much easier!

Reference: https://stackoverflow.com/que...

2018年8月29日 14:37