最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - add multiple function onchange from javascript to the same input - Stack Overflow

programmeradmin4浏览0评论

I want to add multiple function onchange from javascript to the same input. some thik like this:

this.el = document.getElementById(this.docID);

if(x==y)
{

 this.el.onchange += function(){ // some code }

}
if(a==b)
{

 this.el.onchange += function(){  // some code }

}

I want to add multiple function onchange from javascript to the same input. some thik like this:

this.el = document.getElementById(this.docID);

if(x==y)
{

 this.el.onchange += function(){ // some code }

}
if(a==b)
{

 this.el.onchange += function(){  // some code }

}
Share Improve this question edited Oct 7, 2011 at 5:56 Trott 70.2k27 gold badges182 silver badges217 bronze badges asked Jun 25, 2010 at 9:18 user368038user368038 2651 gold badge6 silver badges16 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

If you want to chain onchange functions, you can do something like this:

this.el = document.getElementById(this.docID);

if(x==y) {
  this.el.onchange = function(){ // some code }
}

if(a==b) {
  var oldOnChange = this.el.onchange;
  this.el.onchange = function(){ 
    // execute previous onchange function
    if(oldOnChange) oldOnChange();

    // some code 
  }
}

Like this you can also decide, whether you want the old onchange function to be executed before or after the new onchange code.

Instead of using the onchange attribute, you should think about using addEventListener and the other DOM2 methods. There are some cross-browser issues which crop up (even when using the onchange attribute) so my remendation is to use a library, such as the jQuery change event observer.

Using jQuery, your code example would look like this:

this.el = document.getElementById(this.docID);

if(x==y) {
    $(this.el).change(function() { /* some code */ });
}
if(a==b) {
    $(this.el).change(function() { /* some code */ });
}

You can't add 2 functions together, that code is wrong. There's only 1 onchange function.

So you could do something like this:

this.el.onchange = function() {   
    if(x==y) {
        // some code
    } else if(a==b) {
        // some other code  
    }  
}

this.el.onchange calls a main function after this calling you do parison and calls other function

this.el = document.getElementById(this.docID);

this.el.onchange += functionx();

functionx() {

if(x==y) {

this.el.onchange += functionY(){ // some code }

} if(a==b) {

this.el.onchange += functionZ(){ // some code }
}

}

发布评论

评论列表(0)

  1. 暂无评论