首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >带链接的JavaScript按钮

带链接的JavaScript按钮
EN

Stack Overflow用户
提问于 2018-10-16 04:00:19
回答 5查看 72关注 0票数 -2

我正在尝试设置一个按钮,点击将重定向到一个新的链接。我尝试了这么多不同的选择,但我就是不能让它工作。

代码语言:javascript
复制
var button = document.createElement("button");
button.innerHTML = "$1.00";

divInnerElement.appendChild(button);

button.addEventListener ("click", function() {
  window.location('http://www.google.com','_blank');
  return false;
});  

更新:该函数有效,但它只重新加载当前页面,而不是将您重定向到不同的页面。如果我使用window.open,它可以工作,但我不希望它打开一个新窗口。

更新:

因此,我不确定是什么原因导致在使用window.location时点击,但我能够添加一个aTag到按钮中,然后解决了问题。

代码语言:javascript
复制
<script>
var button = document.createElement("button");
var aTag = document.createElement('a');
aTag.setAttribute('href','http://www.google.com');
aTag.innerHTML = '$1.00';
button.appendChild(aTag);
divInnerElement.appendChild(button);

// button.addEventListener ("click", function() {
//   window.location.href = 'http://www.google.com';
// return false;
// });  
</script>
EN

回答 5

Stack Overflow用户

发布于 2018-10-16 04:22:28

你的问题非常模糊,这里有一些工作代码-希望这是你需要的

Html:

代码语言:javascript
复制
<div id="divInnerElement"></div>

Javascript:

代码语言:javascript
复制
var button = document.createElement("button");
button.innerHTML = "$1.00";

document.getElementById('divInnerElement').appendChild(button);

button.addEventListener ("click", function() {
  window.open('http://www.google.com','_blank');
  return false;
});  

我使用的是window.open:因为您放入了原始的代码片段_blank,所以我假设您希望在新的选项卡中打开该链接。

票数 0
EN

Stack Overflow用户

发布于 2018-10-16 13:47:57

此代码片段应位于页面底部,并从代码中删除返回语句,以便页面将在新选项卡中打开。

代码语言:javascript
复制
 var button = document.createElement("button");
 button.innerHTML = "$1.00";

 document.getElementById('divInnerElement').appendChild(button);

 button.addEventListener ("click", function() {
  window.open('http://www.google.com','_blank');

 }); 
票数 0
EN

Stack Overflow用户

发布于 2018-10-17 00:43:17

因此,我不确定是什么原因导致在使用window.location时点击,但我能够添加一个aTag到按钮中,然后解决了问题。

代码语言:javascript
复制
<script>
    var button = document.createElement("button");
    var aTag = document.createElement('a');
    aTag.setAttribute('href','http://www.google.com');
    aTag.innerHTML = '$1.00';
    button.appendChild(aTag);
    divInnerElement.appendChild(button);

    // button.addEventListener ("click", function() {
    //   window.location.href = 'http://www.google.com';
    // return false;
    // });  
    </script>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52823936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档