我正在尝试设置一个按钮,点击将重定向到一个新的链接。我尝试了这么多不同的选择,但我就是不能让它工作。
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到按钮中,然后解决了问题。
<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>
发布于 2018-10-16 04:22:28
你的问题非常模糊,这里有一些工作代码-希望这是你需要的
Html:
<div id="divInnerElement"></div>
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
,所以我假设您希望在新的选项卡中打开该链接。
发布于 2018-10-16 13:47:57
此代码片段应位于页面底部,并从代码中删除返回语句,以便页面将在新选项卡中打开。
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');
});
发布于 2018-10-17 00:43:17
因此,我不确定是什么原因导致在使用window.location时点击,但我能够添加一个aTag到按钮中,然后解决了问题。
<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>
https://stackoverflow.com/questions/52823936
复制相似问题