简体   繁体   中英

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

<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.

Why not just initially select the li?

$('#t1 li').on("keydown", function () {
    alert('You are typing');
    utility.test(this);
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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