简体   繁体   中英

On click event on HTML requires double click

I have this anchor which has an onclick function that changes the background color of certain div to green. It is properly working but the problem is it needs to be double clicked in order for the function to be executed.

HTML:

<a onclick="btngreen()" href="">MENU</a>

Javascript:

function btngreen(){
    document.getElementById("nameofdiv").style.backgroundColor = 'green';
}

您可以使用ondblclick

<a ondblclick="btngreen()" href="">MENU</a>

As per my understanding of your problem.

Try this code. use # in href

<a onclick="btngreen()" href="#">MENU</a>

or you can use

<a onclick="btngreen()" href="javascript: void(0)">MENU</a>

Works fine for me. Only issue I had was your empty href="" tag so I removed it. You could also use href="#" if you do not want to remove it.

 <script> function btngreen(){ document.getElementById("nameofdiv").style.backgroundColor = "green"; } </script> <a onclick="btngreen()" href="#">MENU</a> <div id="nameofdiv" style="width:100px;height:100px;"></div> 

If you do not need the button to be a link, you could simple change it to another tag such as <p> since the a will be trying to naviagte the page.

<p onclick="btngreen()">menu</p>
<script type="text/javascript">
    function btngreen(){
        document.getElementById("nameofdiv").style.backgroundColor = "green";
    }
</script>

or you could also just default the link to not navigate from the page such as this example below.

<a onclick="btngreen()" href="#">menu</a>
<script type="text/javascript">
    function btngreen(){
        document.getElementById("nameofdiv").style.backgroundColor = "green";
    }
</script>

Using the href="#" is a dead link and will not navigate the page anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM