单击带有href属性的链接并执行Javascript函数
我的脚本包含一个链接单击带有href属性的链接并执行Javascript函数,javascript,html,Javascript,Html,我的脚本包含一个链接a元素,其href属性为“#login”,如下所示 <a href="#login">Login</a> 试试这个: <a href="#login" onclick="getValue()">Login</a> function getValue() { alert("working"); e.preventDefault(); } 函数getValue() { 警惕(“工作”); e、 预防默认值
a
元素,其href
属性为“#login”,如下所示
<a href="#login">Login</a>
试试这个:
<a href="#login" onclick="getValue()">Login</a>
function getValue()
{
alert("working");
e.preventDefault();
}
函数getValue()
{
警惕(“工作”);
e、 预防默认值();
}
您的
getElementsByTagName
将其视为jquery选择器,而不是专门为它设计的
给标签一个id
并使用:
window.onload=function(){
document.getElementById(“loginLink”).onclick=function(e){
e、 预防默认值();
警惕(“工作”);
}
}
为什么我在这些答案中没有看到任何疑问或爱
如果您想使用CSS选择器获取链接,没有任何东西可以阻止您:
window.onload=function(){
document.querySelector(“a[href='#login']”)。onclick=function(e){
e、 预防默认值();
警惕(“工作”);
}
}
<a href="#login" onclick="getValue()">Login</a>
function getValue()
{
alert("working");
e.preventDefault();
}