本文介绍了如何通过jQuery中的.on函数在多个选择器上附加不同的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有以下两个元素:

I have two elements as following on my page:

<input type="text" id="textfield"/>  
<input type="button" id="button" value="CLICK"/>

在我的Javascript代码中,我有以下内容:

And in my Javascript code I have the following:

$(document).ready(function() {  
     $("#button,#textfield").on("click change",function() {
           // This won't work because I don't need click function 
           // to be worked on the text field 
     });
});

我需要单击功能才能在按钮上工作,而只需更改功能就可以在文本字段上工作.我该怎么做?

What I need is click function to be worked on button and need only change function to be worked on text field. How do I do this?

推荐答案

如果希望针对不同对象上的不同事件调用相同的代码,则可以将事件处理代码放入通用函数中,然后指定确切条件在每次活动注册中:

If you want the same code to be called for different events on different objects, you can put the event handling code into a common function and then specify the exact conditions in each event registration:

$(document).ready(function(){  
    function myEventHandler(e) {
        // your code here
    }

    $("#button").on("click", myEventHandler);
    $("#textfield").on("change", myEventHandler);
});

这篇关于如何通过jQuery中的.on函数在多个选择器上附加不同的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 09:43