我有这段代码:
$(document)
.on(
"click",
"#target",
function() {
//SOME_CODE
}
);
现在我必须将 //SOME_CODE
绑定到另一个事件之后,必须仅在第二个事件上执行某些特定代码:
$(document)
.on(
"click",
"#anotherTarget",
function() {
//SOME_OTHER_CODE
//SOME_CODE
}
);
如何在不复制粘贴 //SOME_CODE
的情况下调用而,而无需在两个事件之上指定功能?
我尝试过这段代码:
$(document)
.on(
"click.somecode",
"#target",
function() {
//SOME_CODE
}
);
$(document)
.on(
"click",
"#anotherTarget",
function() {
//SOME_OTHER_CODE
$(document).trigger("click.somecode");
}
);
但 //SOME_CODE
未执行。
答案 0 :(得分:1)
答案 1 :(得分:1)
只为目标触发点击事件?
$(document)
.on(
"click",
"#anotherTarget",
function() {
//SOME_OTHER_CODE
$("#target").click();
}
);
答案 2 :(得分:0)
将//SOME_CODE
放入函数中,然后调用它。例如:
function doSomeCode() {
//SOME_CODE
}
$(document)
.on(
"click.somecode",
"#target",
doSomeCode
);
$(document)
.on(
"click",
"#anotherTarget",
function() {
//SOME_OTHER_CODE
doSomeCode();
}
);
答案 3 :(得分:0)
您可以尝试以下方法:
$(document)
.on(
"click.somecode",
"#target",
function() {
console.log("SOME_CODE");
}
);
$(document)
.on(
"click",
"#anotherTarget",
function() {
console.log("SOME_OTHER_CODE");
$("#target").trigger("click");
}
);
请参阅fiddle