我有 JS 代码,其中使用全局事件处理程序。我所说的全局事件处理程序的意思是:
$(document).on('click', function(e) {
if (e.target.className === 'my-class') {
return e.target.className + ' has been clicked';
}
if (e.target.id === "id1") {
return e.target.id + ' has been clicked';
}
}
我使用单独的事件处理程序 - 示例如下:
$('.my-class').on('click', function(e) {
return this + ' has been clicked';
}
$('#id1').on('click', function(e) {
return this + ' has been clicked';
}
但遇到了关于 if and/or
的问题处理程序中的语句,为了不纠正重复代码,切换到全局事件处理程序 - 例如 if and/or
是这样的:
$(document).on('click', function(e) {
if (e.target.className === 'my-class' || e.target.className === 'my-other-class') {
return e.target.className + ' has been clicked';
}
if (e.target.id === "id1") {
return e.target.id + ' has been clicked';
}
}
(这就是它在各个处理程序上的外观)
$('.my-class').on('click', function(e) {
return this + ' has been clicked';
}
$('.my-other-class').on('click', function(e) {
return this + ' has been clicked';
}
$('#id1').on('click', function(e) {
return this + ' has been clicked';
}
但是,现在我遇到了问题,我的代码变得非常复杂,并且我正在使用 e.target
, e.currentTarget
, $(e.target).children()
,ETC。 - 甚至$(e.target).parents()[i]
在 for loop
看起来像这样:
for (var i = 0; i < $(e.target).parents().length; i++) {
if ($(e.target).parents()[i].className === 'my-class') {
return 'this is annoying';
}
}
这可能会变得非常困惑。
我想切换回单独的处理程序(除非我真的应该使用全局处理程序),但不知道如何处理 if and/or
使用单独的处理程序来零件
有谁知道解决这个问题的方法,或者能够深入了解我应该如何构建我的事件处理程序?
谢谢。
最佳答案
请检查if
语句。你必须写两个 'equal' == ,你只写了一次。
if (e.target.className == 'my-class' || e.target.className == 'my-other-class') {
}
关于javascript - JS/jQuery - 在单个事件处理程序上使用全局事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38774456/