我有一个代码块,我想在触发点击时在不同的场景中调用,具体取决于事件是直接的还是被委派的。
但是在将代码更改为on
时,它只能部分工作。
我有一个代码:
$(document).on('click','.selected-option',function(event){
//lot of code
我想用:
$('.selected-option').click(function(event){ //lots of code }
我想像下一样使用它:
if (some condition)
{
$(document).on('click','.selected-option',function(event){
}
else
{
$('.selected-option').click(function(event){
}
并希望使用相同的代码。
答案 0 :(得分:7)
您没有拥有来使用匿名函数来处理事件。只需编写常规函数:
function handleClick(event) {
// lots of code
}
然后将函数绑定到任意数量的事件:
if (some condition) {
$(document).on('click','.selected-option', handleClick);
else {
$('.selected-option').click(handleClick);
}
答案 1 :(得分:-1)
定义一个函数并完成工作;
var funCalled = function(){
//your detailed actions
}
并在不同条件下调用它!
if (some condition) {
$(document).on('click','.selected-option',function(event){
funCalled()
})
} else {
$('.selected-option').click(function(event){
funCalled()
});
}
答案 2 :(得分:-1)
var testfunction = function(currentObj){
// your code here
}
if (some condition)
{
$(document).on('click','.selected-option',function(event){
testfunction($(this));
});
}
else {
$('.selected-option').click(function(event){
testfunction($(this));
});
}