如何更改url的元素并使用javascript在新选项卡中打开它?

问题描述 投票:0回答:4

当前网址

https://example.com/render.php#url=[Media_URL]

我想修改当前的url,这样当我点击一个按钮时,它会在浏览器上打开一个带有修改过的URL的新标签:

https://example.com/convert/index.php?url=[Media_URL]&&ftype=mp3

[Media_URL]是一个可重用的变量。

我怎么能用JavaScript做到这一点?

提前致谢!

javascript html
4个回答
0
投票

HTML

<button id="myButton">
</button>

使用Javascript

document.getElementById('myButton').onclick = function() {
    var Media_URL = window.location.href.split("#url=")[1];
    var url = 'https://example.com/convert/index.php?url=' + Media_URL + '&&ftype=mp3';
    window.open(url, '_blank').focus();
};

说明

要从Javascript中的URL获取值,请使用window.location.href

然后你可以用.split("#url=")解析它,创建一个数组,第二个元素[1]将拥有URL的正确部分,在你的例子中包含Media_URL。

要在新标签页中打开,请使用window.open(url, '_blank')


0
投票

要获得当前的url,您可以使用:window.location.href。要重定向到新标签,请阅读window.open()上的w3schools文档。


0
投票

也许使用标签<button><a>嵌套,在新标签的属性中使用target="_blank"

<a href="#" target="_blank"><button>.</button></a> 

要么

 <a href="#" class="btn">.</a>

0
投票

正如其他人已经声明使用window.open()但你需要知道用户的浏览器设置可能会阻止窗口打开。

let blocked = false
try {
  const nu = window.open('https://google.com', '_blank');
  if (nu === null) {  // built-in blocking makes this null
    blocked = true;
  }
} catch (ex) {  // popup-blocking plugins make it raise an error
  blocked = true;
}

if (blocked) {
  alert('blocked!');
}

console.log(blocked)
// If it returns null or an error it's blocked

https://developer.mozilla.org/en-US/docs/Web/API/Window/open

© www.soinside.com 2019 - 2024. All rights reserved.