Javascript触发两个事件-onkeypress和onclick

pod*_*eig 5 events onclick javascript-events onkeypress

问题是当我在单选按钮上按下一个键时,元素MyFunc会触发两次-一次是针对“ onkeypress”事件,另一次是“ click”事件。

问题“为什么?” 我需要通过两种不同的方式来处理此问题,但是现在我无法识别什么是初始事件。当我单击鼠标时,仅触发“单击”事件。

<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
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

hun*_*ter 0

您可以向函数添加第三个参数

function MyFunc(e, obj, click) {
    if (click) { } // do stuff
    else { } // do other stuff
}
Run Code Online (Sandbox Code Playgroud)

现在向您的事件添加一个布尔值...

<input type="radio" onkeypress="MyFunc(event, this, false)" onclick="MyFunc(event, this, true)" name="myList" id="MyId_1" />Topic 1
<input type="radio" onkeypress="MyFunc(event, this, false)" onclick="MyFunc(event, this, true)" name="myList" id="MyId_2" />Topic 2
Run Code Online (Sandbox Code Playgroud)