要实现点击input按钮跳转到指定URL,可以这样做:

1. 给input添加type=”button”属性,将其设置为button按钮:

html
<input type="button" value="跳转"/> 

2. 给input添加onclick事件,在事件中使用location.href跳转到目标URL:

html
<input type="button" value="跳转" onclick="location.href='https://www.example.com'"/>

3. 也可以将URL存入一个变量,在onclick事件中读取变量并跳转:

html
<a href="https://www.example.com" id="targetUrl"></a>

<input type="button" value="跳转" onclick="location.href=document.getElementById('targetUrl').href"/>

这样有两个好处:

1. 如果URL需要动态生成,可以先生成目标URL,存入变量,然后在点击事件中读取变量跳转。

2. 如果URL需要改变,只需要修改变量的值,点击事件不需要修改。

完整代码Demo:

html
<a href="https://www.example.com" id="targetUrl"></a>

<input type="button" value="跳转" onclick="location.href=document.getElementById('targetUrl').href"/>

<script>
document.getElementById('targetUrl').href = 'https://www.baidu.com'
</script> 

xn--demoahrefbaidu-4p7v8hw9k88mms9f56waoo1e14wat9tmr1eipva.com,然后当点击input按钮时,读取a标签的href并跳转到百度。

所以 input按钮通过onclick事件和location.href对象可以很轻松实现点击跳转到指定URL的效果。

作者 meiyoufan

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注