如何在html链接中添加onclick效果(<a>) using javascript?

时间:2015-07-09 13:30:32

标签: javascript html onclick

I'm sitting here with a school project, I've done a bunch og html and css, now it's time for the Javascript to apply. My question is, how to add an onclick effect to a link? this is what I have already, I can't seem to figures this function out, yet.

 <li><a id="male" onclick=")" href="#male">Male</a></li> 

and the script that didn't work:

<script> 
    function maleFunction(el) {
    document.getElementById(male).style.border = "1px solid black";
    }

</script>

trying to add a border when I click the link element, Male, what am I doing wrong?

1 个答案:

答案 0 :(得分:4)

onclick的内容有误。它应该是:

 <li><a id="male" onclick="maleFunction(this)" href="#male">Male</a></li>

在函数末尾给出return false;。您需要将male更改为el,因为您已经在提及它了。

function maleFunction(el) {
    el.style.border = "1px solid black";
    return false;
}

对这些情况使用事件委托和事件处理程序总是更好。在你的情况下,它应该是这样的:

<li><a id="male" href="#male">Male</a></li>

您已经拥有id。所以这很容易实现:

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中使用类似的东西:

.selected {border: 1px solid black;}

现在将该类添加到特定元素:

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");
}