开发者

jQuery set call back on child elements

I am trying to attach an onChange callback to all the input elements under the div #dim. It selects all 3 input elements, but returns an exception:

Uncaught TypeError: Object 0 has no method 'change'

It may be because x may not 开发者_开发知识库be a jQuery object. How would I make this work?

function registercb() {
    var sel = $("div.dim > input");
    for (x in sel) {
        x.change(function() {
            dosomething();
        });
    }
}


You can simply do:

function registercb() {
   $("div.dim > input").change(dosomething);               
}

A few things to watch for:

  • Inside that iteration (don't use this, see the next point) x is the DOM element, not a jQuery object which has the .change() method, you would need to wrap it in a jQuery object like $(x), but again that isn't the correct solution here.
  • Don't use a for(...in...) loop to iterate an object (a jQuery object is array-like), that type of loop is for enumeration.
  • Most jQuery functions (almost all) run on more than one element, so just run it on the set to affect all elements, .change() is one of these.
  • In the cases you do need to loop, check out .each(), as it'll make your life much easier, don't use this here, it's only an example of what it would look like:

Example:

function registercb() {
   $("div.dim > input").each(function() {
      $(this).change(dosomething);               
   });
}


You don't have to loop over the elements. You can think of a jQuery object as holding a collection. When you do:

var sel = $("div.dim > input");

It means that sel has all the input elements in it, so then when you run a method like change() it will affect all of the elements in the collection. Thus you can do something like this:

function registercb() {
  $("div.dim > input").change(function(){
    dosomething();
  });
}

Bonus knowledge: Now your problem is that when you were doing for( x in sel ) you are getting a lot of stuff on the jQuery object itself that you don't want. If you run the following code in chrome you'll see it outputting a lot unexpected stuff:

for( x in sel ){
  console.log( x );
}

Instead jQuery has the each that lets you loop over the things you want:

sel.each(function(index, item){
  console.log(item);
});

You can even use it on other things, which is really handy!

$([1,2,3]).each(function( index item ){
  console.log( item );  // 1,2,3
})


Assuming your 'dim' div has an ID rather than a class of dim, you can simply do this:

$("#dim > input").change(function() { dosomething(); });

Working example.

In the text you refer to #dim whereas in the code you're refering to .dim - # selects by ID and . selects by class, so if your div is in the format <div id="dim"> then you won't find any matched elements with div.dim as your selector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜