[英]Calling OnClick() twice causes OnClick to not work
I have a table of cells, when a cell is clicked an event is triggered. 我有一个单元格表,单击一个单元格时会触发一个事件。 I want to add cells dynamically so I will call OnClick again on all rows.
我想动态添加单元格,因此我将在所有行上再次调用OnClick。 When I call OnClick for the second time, any cells that have OnClick called twice stop firing any events.
当我第二次调用OnClick时,任何两次调用OnClick的单元格都会停止触发任何事件。
The odd thing is at the event of my OnClick function, if I can "Return;" 奇怪的是,如果我可以“返回”,就使用OnClick函数。 it works, however it throws an error saying "Return" isn't defined
它有效,但是会引发错误,提示未定义“返回”
function initBox() {
$(".selectable").on('click', function (event) {
//if its selected already, unselect it
if ($(this).hasClass('rowHighlightColor')) {
$(this).removeClass("rowHighlightColor");
selectedCellList = null;
}
else {
//unselect previous cell
if (selectedCellList != null) {
selectedCellList.removeClass("highlighted");
}
selectedCellList = $(this);
$(this).addClass("rowHighlightColor");
}
Return;
});
}
it needs to be return
instead of Return
(capital R) 它需要
return
而不是Return
(大写R)
however, writing return;
但是,写
return;
returns undefined
so you can just omit it. 返回
undefined
因此您可以忽略它。
edit: 编辑:
you attach the event twice, make sure only to attach it once, else it causes (as you noticed) undesired behaviour like attaching class and immediately removing it again. 您将事件附加两次,请确保仅将其附加一次,否则会(如您所注意到的那样)引起不良行为,例如附加类并立即将其再次删除。
The reason why it works with "Return" is that the function is only run once because it throws an error when reaching it. 它与“返回”一起使用的原因是该函数仅运行一次,因为到达该函数时会引发错误。
Use jQuerys .live()
(or .on()
for newer versions, as live is deprecated there) to automatically attach the click event to every new row you add. 使用jQuerys
.live()
(或新版本的.on()
,因为不推荐使用live)来将click事件自动附加到您添加的每个新行。 jQuery live Docs jQuery Live文档
You are adding multiple event handlers to existing cells. 您正在向现有单元添加多个事件处理程序。 This is one reason why I prefer to use just the plain old
.onclick
property. 这就是为什么我只使用普通的旧
.onclick
属性的原因之一。
Anyway, to solve this issue you can either only apply the event to the new cells, or add an attribute to them when you do add an event, then check that attribute before adding the event again. 无论如何,要解决此问题,您可以仅将事件应用于新单元格,或者在添加事件时向其添加属性,然后在再次添加事件之前检查该属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.