Binding dynamically added elements in jQuery mobile

删除回忆录丶 提交于 2019-12-17 14:56:36

问题


I'm trying to delete some list elements after dynamically adding them.

The idea is that you can update the list, and then after updating it you can click on a list item to delete it.

Html:

<p>Test</p>
<ul data-role="listview">
    <li>Acura</li>
    <li>Audi</li>
    <li>BMW</li>
    <li>Cadillac</li>
    <li>Ferrari</li>
</ul>
<br>
<input type="button" value="Update" id="button">

Javascript:

var new_list =
    '<ul data-role="listview">' +
    '<li class="delete">Dog</li>' +
    '<li class="delete">Cat</li>' +
    '</ul>';

$('#button').off('click').on('click', function () {
    $('ul').remove();
    $('p').after(new_list);
    $('ul').listview();
});

$('.delete').off('click').on('click', function () {
    $( this ).remove();
});

Jsfiddle Link


回答1:


The correct way to bind events to dynamically added items is as follows.

$(document).on("event", ".selector", function () {
  $(this).remove();
  $('ul_selector').listview('refresh');
});


来源:https://stackoverflow.com/questions/20431392/binding-dynamically-added-elements-in-jquery-mobile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!