如何使用javascript在html链接()中添加onclick效果?
我坐在这里做一个学校项目,我已经做了一系列的html和css,现在是应用Javascript的时候了。 我的问题是,如何为链接添加onclick效果? 这是我已经做过的,我似乎还不能计算出这个函数如何使用javascript在html链接()中添加onclick效果?,javascript,html,onclick,Javascript,Html,Onclick,我坐在这里做一个学校项目,我已经做了一系列的html和css,现在是应用Javascript的时候了。 我的问题是,如何为链接添加onclick效果? 这是我已经做过的,我似乎还不能计算出这个函数 <li><a id="male" onclick=")" href="#male">Male</a></li> 还有不起作用的脚本: <script> function maleFunction(el) { docum
<li><a id="male" onclick=")" href="#male">Male</a></li>
还有不起作用的脚本:
<script>
function maleFunction(el) {
document.getElementById(male).style.border = "1px solid black";
}
</script>
当我单击link元素时试图添加边框,Male,我做错了什么 你的onclick内容是错误的。应该是:
<li><a id="male" onclick="maleFunction(this)" href="#male">Male</a></li>
对于这些情况,最好使用事件委派和事件处理程序。在您的情况下,应该是这样:
<li><a id="male" href="#male">Male</a></li>
document.querySelector("male");
获得元素后,只需添加事件处理程序:
document.querySelector("male").onclick = function () {
// Note the above line, it is an anonymous function without a name.
// You can use "this" to refer the current object.
this.style.border = "1px solid black";
}
使用内联样式不是一个好主意。因此,在CSS中使用如下内容:
.所选{边框:1px纯黑色;}
现在将该类添加到特定元素:
document.querySelector("male").onclick = function () {
// Note the above line, it is an anonymous function without a name.
// You can use "this" to refer the current object.
this.classList.add("selected");
}
你认为onclick=实际上会做什么?
document.querySelector("male").onclick = function () {
// Note the above line, it is an anonymous function without a name.
// You can use "this" to refer the current object.
this.classList.add("selected");
}