Bon*_*Jon 10 html javascript css
我对该链接的新标签有疑问.
无论如何我可以在用户点击链接之前设置浏览器标签标题吗?如果新选项卡中包含的html没有title属性,似乎没有办法讨论新选项卡的标题.我对吗?如何设置标题?
//the href is dynamic so I can't set them one by one because I have 100+ html file here
<a href="test.html" target="_blank">open me<a>
Run Code Online (Sandbox Code Playgroud)
正如您所知,这是不可能的,因为您的链接只是普通的HTML链接.当新页面在新选项卡中打开时,当前页面将不会对其进行任何引用,因此无法以任何方式更改它.您需要使用javascript打开页面并以此方式设置标题.
您可以动态设置它window onload以查找所有a标记并添加一个click事件,打开窗口并设置标题.
如果您希望每个页面都有不同的标题,则可以将其存储data-在a标记的属性中.
请注意,这只适用于同一域中的页面(为了安全起见),并且它不会处理人们右键单击并按"在新窗口中打开".然而,在Windows中进行中键单击确实有效.
HTML
<a href="test.html" data-title="A new page" target="_blank">open me</a>
Run Code Online (Sandbox Code Playgroud)
JavaScript的
window.addEventListener("load", function() {
// does the actual opening
function openWindow(event) {
event = event || window.event;
// find the url and title to set
var href = this.getAttribute("href");
var newTitle = this.getAttribute("data-title");
// or if you work the title out some other way...
// var newTitle = "Some constant string";
// open the window
var newWin = window.open(href, "_blank");
// add a load listener to the window so that the title gets changed on page load
newWin.addEventListener("load", function() {
newWin.document.title = newTitle;
});
// stop the default `a` link or you will get 2 new windows!
event.returnValue = false;
}
// find all a tags opening in a new window
var links = document.querySelectorAll("a[target=_blank][data-title]");
// or this if you don't want to store custom titles with each link
//var links = document.querySelectorAll("a[target=_blank]");
// add a click event for each so we can do our own thing
for(var i = 0; i < links.length; i++) {
links[i].addEventListener("click", openWindow.bind(links[i]));
}
});
Run Code Online (Sandbox Code Playgroud)