jQuery bind event on dynamic element for focus, keypress, keydown, keyup didn't work

StackOverflow https://stackoverflow.com/questions/19878209

  •  30-07-2022
  •  | 
  •  

سؤال

<div id="t1" contenteditable="true" style="width: 400px; height: 200px;">
    <ul>
        <li style="list-style-type: none;">Apple</li>
    </ul>
</div>    <span id="dd"></span>

<script>
$(function () {
    event.returnValue = false;
    $('#t1>ul').on("click", 'li', function () {
        utility.test(this);
    });
});

var utility = {
    test: function (elem) {
        var $this = $(elem);
        $('#dd').html($this.html());
        if (event.preventDefault) event.preventDefault();
    }
}

above code is work fine, but if I change bind event from click to keydown as below

$('#t1>ul').on("keydown", 'li', function () {

then it's didn't work. I am using jQuery version 1.9.1, and try using .live for version 1.8.3, but still didn't work.

Thanks a lot.

هل كانت مفيدة؟

المحلول

The tag with the contenteditable flag will capture and emit the keydown event, not content within it. Simply put, your <li> is not emitting the keydown event.

نصائح أخرى

Why not just initially select the li?

$('#t1 li').on("keydown", function () {
    alert('You are typing');
    utility.test(this);
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top