admin管理员组

文章数量:1410737

I have a list, and within this list im trying to call a function when keyisdown/onfocus/etc? This wont trigger the function:

 <li onkeydown="myFunction()"></li>

The normal onclick works fine(calling the function when the "click is going up") and will trigger the function:

<li onclick="andrafarg()"></li>

So my question is: How can i call this function when the list is clicked immediately down?

I have a list, and within this list im trying to call a function when keyisdown/onfocus/etc? This wont trigger the function:

 <li onkeydown="myFunction()"></li>

The normal onclick works fine(calling the function when the "click is going up") and will trigger the function:

<li onclick="andrafarg()"></li>

So my question is: How can i call this function when the list is clicked immediately down?

Share Improve this question asked May 8, 2015 at 14:35 MattiasMattias 3,1995 gold badges32 silver badges49 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

From the jQuery docs:

The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

So as li elements can't get focused, the keydown-event will never be triggered. For a reference for focusable elements, you might have a look at this answer.

But because of the event-bubbling, an input-field inside the list will trigger the keydown-event, if the event-listener is registered on the input itself or a parent-element. Example:

HTML

<ul>
    <li><input type="text" /></li>
</ul>

Javascript

$('ul > li').on('keydown', function(){
   alert('Event triggered'); 
});

Demo

本文标签: javascriptHow to call onkeydownonfocus to a list tagStack Overflow