gpt4 book ai didi

javascript - jQuery 元素创建中的错误?

转载 作者:数据小太阳 更新时间:2023-10-29 06:03:54 24 4
gpt4 key购买 nike

$(文档).ready(函数(){ var _new_li = $('', { 'id': 'p', '文本':'点击我', 点击:函数(){ 警报('解雇'); },
数据: { '一些数据':'一些数据',
});

_new_li.appendTo($("#example"));
});

当我尝试单击我这样创建的元素时,收到“Uncaught TypeError: Cannot read property 'click' of undefined”。但是,如果您切换 click: 和 data: 它会起作用。

$(document).ready(function(){
var _new_li = $('<li/>', {
'id': 'p',
'text': 'CLICKME',
data: {
'somedata': 'somedata',
},
click: function(){
alert('fired');
}
});

_new_li.appendTo($("#example"));
});

对这种行为有什么解释吗?

亲切的问候

--安迪

附言:

我之前在 jQuery Core Development 论坛上发布了类似的行为,Swedberg 先生在那里回答:

I'm pretty sure this is happening because you're setting data with an object, which >(until 1.4.2) would overwrite the event object. Not sure which version of jQuery you're >using in your project, but it looked like the jsbin example was using 1.4. Try upgrading >to 1.4.2 and see if that helps.

但是1.4.2好像还是有问题

最佳答案

帖子已重写。

你不应该把那个逗号放在数据中最后一个(也是唯一一个)元素之后。

在尝试了一些东西之后,我得到了这个:

$(document).ready(function(){
var fun=function(){
alert('fired');
};
var parms={
'id': 'p',
'text': 'CLICKME',
'click':fun,
'data': {
'somedata': 'somedata'
}
};
console.log(parms);
var _new_li = $('<li/>',parms);

_new_li.appendTo($("#example"));
});

一切正常,直到我点击 li 元素。然后我得到 e is undefined (jquery line 55)。交换点击和数据时效果很好。

仍在调查中

并找到它

jquery开发版,第1919行

var events = jQuery.data(this, "events"), handlers = events[ event.type ];

事件 未定义。

jquery 覆盖存储在数据中的事件。

所以这是一个错误。它应该只是扩展。

我已提交错误报告。

关于javascript - jQuery 元素创建中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com