简体   繁体   English

HTML上的点击事件需要双击

[英]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. 我有这个锚,它具有onclick函数,可将某些div的背景颜色更改为绿色。 It is properly working but the problem is it needs to be double clicked in order for the function to be executed. 它可以正常工作,但问题是需要双击才能执行该功能。

HTML: HTML:

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

Javascript: 使用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 在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. 我唯一遇到的问题是您的空href=""标签,因此我将其删除。 You could also use href="#" if you do not want to remove it. 如果您不想删除它,也可以使用href="#"

 <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>因为a会尝试导航该页面。

<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. 使用href="#"是无效链接,并且不会在任何地方浏览页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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