开发者

jQuery variables for multiple events

I'd like to be able to define the variable which I can then use for other开发者_如何学Go events, such as mouseout, mouseenter, click etc.

This is the current code:

   $('a div')

    // Get the width an height of the image
    //var $img_width = $(this).children('img').width();
    //var $img_height = $(this).children('img').height();

    .mouseenter(function() {
        alert($img_width)

    })
    .mouseleave(function() { // Animate the image back to it's original size
        alert($img_width);
    })
    .each(function(index) {
        alert($img_width);
    });


Try this, this should provide you with the event handling you need, on mouseover and mouseout. Everytime you mouseover a picture you can refer it with $(this), so in this live handler you can do what ever you want with the specified element.

There's loads of other events that live can handle too, please read up on it if you want. http://api.jquery.com/live/

$('a div').live('mouseover mouseout', function(event) {

    var $img_width = $(this).children('img').width();

    if(event.type == 'mouseover'){
        //do stuff on mouse over
    }
    else if(event.type == 'mouseout'){
        //do stuff on mouseout
    }

    alert($img_width);

});

EDIT I see you're checking for children in the div you have the event bound to. You would probably be better of referencing the img directly in the event handler. Then you can get the width right away without having to traverse the DOM.

$('a div img').live('mouseover mouseout', function(event) {

Good luck!


If you swap your code around a bit, you can use the closure that .each() creates to your advantage, like this:

$("a div").each(function(index) {
  var $img_width = $(this).children('img').width();
  var $img_height = $(this).children('img').height();

  $(this).mouseenter(function() {
    alert($img_width)
  }).mouseleave(function() {
    alert($img_width);
  });

  alert($img_width);
});

You can test it out here.

This defines the variables for each matched elements, and that's the value you'll get in the bound functions, specific to each <div> like you want. As a side note, <div> (or any block element) isn't a legal child of <a>, so you may want to revisit the markup if possible. ​

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜