用jquery动态写出li。元素写入后不可点击
我有一个函数,当选中一个复选框时,我动态地将 li 写入空的 ol 中。
代码:
$(":checkbox").click(function() {
var checkedState = $(this).is(':checked');
if (checkedState == true) {
var productName = $(this).attr("title");
$("#selectedProductsList").append("<li class=\"productList " + this + "\"><p class=\"removeIcon\"><img src=\"images/remove-icon.png\" alt=\"Remove Product\" /></p><span class=\"productName\">"+ productName +"</span></li>");
};
});
然后,当写出时,会出现一个删除图标,单击该图标将从 ol 中删除该项目。这个删除图标有一个removeIcon类,可以在上面的动态li中看到。
我有一个函数可以处理删除调用,然后执行一些操作: 代码:
$('.removeIcon').click(function() {
alert("starting");
});
现在我有删除操作,只是想提醒一条消息,它被调用了。但似乎没有进入功能。
除了 .click 方法之外,我还需要通过某种方式访问这些动态 li 吗?我看到了这个帖子: 使用 $.click() 动态插入的 DOM 元素不可点击< /a>
他们添加了 .live 与 .click,但这似乎也不起作用。
有什么想法吗?
I have have a a function that when a checkbox is checked i dynamically write out an li into a ol that is empty.
Code:
$(":checkbox").click(function() {
var checkedState = $(this).is(':checked');
if (checkedState == true) {
var productName = $(this).attr("title");
$("#selectedProductsList").append("<li class=\"productList " + this + "\"><p class=\"removeIcon\"><img src=\"images/remove-icon.png\" alt=\"Remove Product\" /></p><span class=\"productName\">"+ productName +"</span></li>");
};
});
Then when that writes out there is a remove icon that will remove the item from the ol when clicked. This remove icon has a class of removeIcon which can be seen in the dynamic li above.
I have a function that processes the remove call and then does some actions:
Code:
$('.removeIcon').click(function() {
alert("starting");
});
Right now i have the remove action just trying to alert a message that it got called. But it seems that it is not getting into the function.
Is there a certain way that i need to access these dynamic li's other then the .click method? I saw this post:
Dynamically Inserted DOM Elements are not Clickable using $.click()
Where they added .live vs .click but this doesn't seem to work either.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用现场活动...
try using the live event...
您需要对动态添加的元素使用
live()
($(":checkbox").live('click', ...)
),因为click()
只会运行一次,并且只会捕获到目前为止存在的元素。You need to use
live()
for dynamically added elements ($(":checkbox").live('click', ...)
), becauseclick()
will only run once and will only catch elements that exist up to this point.使用
.delegate()
而不是live().
使用
.live()
会非常浪费,因为您所定位的元素似乎都在同一个容器中。Use
.delegate()
instead oflive()
.It would be extremely wasteful to use
.live()
since it appears that the elements you're targeting are all in the same container.如果有想法,为什么不把按钮放在一个对象中呢?这是一个小例子(未经测试,它可以帮助您实现想法,但应该可行)
If got a idea, why dont u put you button in a object? here a little example(NOT TESTED its for helping you on a idea, but should work)