Javascript fires two events - onkeypress and oncli

2019-05-04 19:52发布

Problem is when I press a key over a radio button, element MyFunc fires twice - once for "onkeypress" event, another time for "click" event.

Question "Why?" I need to handle this by two different ways, but now I can not recognize what initial event was. When I click a mouse it fires just for "click" event.

<ul>
    <li>
        <input type="radio" onkeypress="MyFunc(event, this)" onclick="MyFunc(event, this)" name="myList" id="MyId_1" />Topic 1
        <input type="radio" onkeypress="MyFunc(event, this)" onclick="MyFunc(event, this)" name="myList" id="MyId_2" />Topic 2
    </li>
</ul>

function MyFunc(e, obj) {
    alert(e.type); // alerts "keypress" and then "click"
    // Do my stuff
}

Thank you for help!

7条回答
何必那么认真
2楼-- · 2019-05-04 20:46

If 2 events are being fired during pressing a key then check event.detail property in onClick function. if event.detail = 0 then it means that mouse was not clicked on that element and we can ignore it. event.detail

查看更多
登录 后发表回答