【问题标题】:How do you link to a website with a button that has a function providing the link?您如何使用具有提供链接功能的按钮链接到网站?
【发布时间】:2020-06-27 03:44:06
【问题描述】:
我正在使用一个函数将字符串返回给单击按钮。该字符串包含指向 google 的链接。当我按下按钮时,它不会重定向到谷歌。我对使用 html 和 java 很陌生。
<button id="linkBtn" type="button" onclick="window.location.href = getGoogleLink();">Google</button>
<script>
function getGoogleLink(){
string google = "'https://www.google.com/'"
return google;
}
</script>
【问题讨论】:
标签:
javascript
html
function
button
hyperlink
【解决方案1】:
我对使用 html 和 java 非常陌生。
你的意思是 JavaScript。
请看下面的帖子。它通过 JavaScript 处理重定向。 How do I redirect to another webpage?
请不要使用 HTML 事件处理程序注册属性onclick。这是不好的做法。将 ID 添加到 DOM 元素并在 JavaScript 中执行所有操作。
(() => {
window.addEventListener('load', () => {
// get the button element from your HTML
const btn = document.getElementById('btn');
// register click listener
btn.addEventListener('click', () => {
window.location.href = "https://google.com/";
});
});
})();
<button id="btn">Redirect to Google</button>
【解决方案2】:
您需要使用location.replace('address')。
例如
<button id="linkBtn" onclick="redirect('https://www.google.com/')" type="button">Google</button>
<script>
function redirect(url) {
location.replace(url)
}
</script>
在顶部,我写了一个获取 URL 和更改窗口位置的函数,URL 来自:
onclick="redirect('https://www.google.com/')"