如何将超链接设置为变量

How to set a hyperlink as a variable

本文关键字:变量 设置 超链接      更新时间:2023-09-26

我有以下代码:

<div><input id="ShopButton" type="button" onclick="window.location.href='http://www.hyperlinkcode.com/button-links.php'"</div>

工作正常,除了现在我的超链接将是动态的。所以我的问题是,我怎么能设置一个变量,然后传递给onclick事件?超链接将存储在一个名为StrUCode的变量中。

我知道我必须声明变量,但我如何将它工作到我的按钮?

我正在摸索html/javascript,刚刚开始涉水。

谢谢

如果你不想像我一样使用内联js:

var StrUCode = "http://example.org";
document.querySelector("#ShopButton").addEventListener("click",function(){
    window.location.href=StrUCode;
},false);

使用EventTarget.addEventListener ();监听元素上的事件,如:click, mouseover


//You can use functions too:
var StrUCode = "http://example.org";
document.querySelector("#ShopButton").addEventListener("click",function(){
    redirectMe(StrUCode);
},false);
function redirectMe(url){
    window.location.href=url;
};