Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Binding dynamically added elements in jQuery mobile

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...