Detecting which list element was clicked using jquery (list is added dynamically)

前端 未结 1 1416
不思量自难忘°
不思量自难忘° 2021-01-29 16:01

Case1: List is present in the html already

  • One
  • Two

The cl

相关标签:
1条回答
  • 2021-01-29 16:46

    Assuming that you've got jQuery correctly loaded, and that you put your jQuery related code in a "document ready" handler, I'd recommend "event delegation", such that you just register a single event handler on a static ancestor element.

    Clicks received in the li descendants will "bubble up" to the ancestor element, but jQuery will ensure that this is set to the element that was actually clicked:

    $('#testDiv').on('click', 'li', function() {
        console.log(this);
    });
    

    So long as the static ancestor remains present on the page you can dynamically change its contents as much as you please and the event handler will continue to work.

    0 讨论(0)
提交回复
热议问题