在 jQuery mobile 中绑定动态添加的元素 [英] Binding dynamically added elements in jQuery mobile

查看:19
本文介绍了在 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 链接

推荐答案

将事件绑定到动态添加项的正确方法如下.

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

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

这篇关于在 jQuery mobile 中绑定动态添加的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆