为什么$()。click()不能在pageinit生成的上工作?
click函数适用于作为HTML一部分的
元素。 我无法弄清楚为什么不。 (此代码具有运行所需的全部function)
My Title
Hello world
//Why is delete button not firing? $('#thelists').bind('pageinit', function(event) { console.log('in bind pageinit for yourlists'); var thelists = ["list1", "list2"]; console.log(thelists); $.each(thelists, function(index, alist) { $('#allyourlists').append('List: ' + alist + ' '); }); $('#allyourlists').listview('refresh'); }); //gets the val of val1 from the previois call $("#delalist").click(function (e) { e.stopImmediatePropagation(); e.preventDefault(); alert ('in delalist') ; });
使用已弃用的live
函数:
$("#delalist").live('click',function (e) { e.stopImmediatePropagation(); e.preventDefault(); alert ('in delalist') ; });
或者使用(jQuery> 1.7):
$('body').on('click', "#delalist", function (e) { e.stopImmediatePropagation(); e.preventDefault(); alert ('in delalist') ; });
另外我建议使用一个class
而不是id
因为id
应该是唯一的
使用或delegate
事件来处理动态创建的元素。
使用on
(jQuery ver 1.7+)
$('body').on('click', "#delalist", function (e) { e.stopImmediatePropagation(); e.preventDefault(); alert ('in delalist') ; });
使用delegate
$('body').delegate("#delalist", 'click', function (e) { e.stopImmediatePropagation(); e.preventDefault(); alert ('in delalist') ; });
on()
参考: http : //api.jquery.com/on/ jQuery ver 1.7+
delegate()
参考: http : //api.jquery.com/delegate/
ID是独一无二的,您正在重复使用“delalist”。
对于将动态插入dom的所有元素,您应该使用.live或.delegate而不是.bind。
使用.delegate比.live更受欢迎,因为.live会扫描任何dom更改以绑定事件。 阅读.live vs .delegate 。
使用.delegate –
$(document).delegate('#thelists', 'pageinit', function () {
使用.live –
$('#thelists').live('pageinit', function(event) {
和
使用.delegate –
$("#thelists").delegate('#delalist', 'click', function (e) {
使用.live –
$("#delalist").live('click', function (e) {
我不确定你在这里想做什么,但我想我找到了一些可能有用的东西。 当我加载你的代码并按照它列出的方式运行它时,我发现第一个按钮,当我点击它时提示回用户。 所以我改变了:
data-role="button" id="delalist">List0:
读作:
data-role="button" id="deallist">List0:
这有帮助吗?