[英]How to call the same function in two different ways?
I am trying to combine a function which will display alert (ofcourse I have a lot of code In this function but for this case It will be alert) after: 我正在尝试在以下情况下组合一个显示警报的功能(当然,在此功能中我有很多代码,但在这种情况下,它将是警报的)
Click
on element with class .number
Click
类为.number
元素 Change
select[name=receive]
Change
select[name=receive]
I have this code but it doesn't work: 我有此代码,但它不起作用:
$(document).on(("click",".number"),("change","select[name=receive]"),function(){
alert('test');
})
Try this 尝试这个
$(document).on("click change","select[name=receive], .number", function(){
alert('test');
});
Or 要么
var fn = function () {
alert('test');
}
$(document).on("click", ".number", fn);
$(document).on("change", "select[name=receive]", fn);
Try this 尝试这个
function doMyWork() {
console.lot( 'TEST' );
}
$('.number').on('click', doMyWork);
$('select[name=receive]').on('change', doMyWork);
Or, if your elements are inserted after DOM ready: You do not have to use this form if the target elements exist at DOM ready
或者,如果在DOM准备就绪后插入了元素: 如果目标元素在DOM ready
存在,则不必使用此表单
function doMyWork() {
console.lot( 'TEST' );
}
$(document).on('click', '.number', doMyWork)
.on('change', 'select[name=receive]', doMyWork);
You cannot separate events and selectors in a single .on()
call. 您不能在单个.on()
调用中分隔事件和选择器。 You have two options here. 您在这里有两个选择。 You can use them together.... 您可以一起使用它们。
$(document).on("click change", ".number, select[name=receive]"),function(){
alert('test');
});
...however this means that .number will listen to both click and change, possible resulting in the function running 2 times. ...但是,这意味着.number将同时监听点击和更改,可能导致该函数运行两次。
You need to move the function outside and reuse it for every handler 您需要将函数移到外部并为每个处理程序重用
var al = function(){
alert('test');
};
$('.number').on('click', al);
$('select[name=receive]').on('change', al);
$(document).on("click change",".number, select[name=receive]", function(){
alert('test');
})
I am not sure where you learned that syntax, but that is not how on() works. 我不确定您从哪里学到的语法,但是那不是on()的工作原理。
Use a named function and share it. 使用命名函数并共享它。
(function(){
var shared = function(){
console.log(this);
}
$(document)
.on("click",".number", shared)
.on("change","select[name=receive]", shared);
}());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.