2010-10-12 64 views
0

我正在为客户建立一个摄影组合,并决定让它更具互动性。我摆脱了网站上的所有按钮,并让用户使用击键与网站进行交互。我原来的代码使用:你如何使用jquery .live()和按键?

$(document).bind('keydown', function(e) { 

但这不幸的是不会允许用户与通过jquery加载的图片进行交互。所以访客只能与第一张照片互动。我环顾四周,发现.live()方法应该将事件绑定到所有对象上,无论文档加载时加载还是事后加载。但由于某种原因,它不适用于我的代码。我正在使用jquery 1.4.2,这是我的代码样本:

$(document).live('keydown', function(e) { 

if (e.keyCode == 32) { 

    var imgwidth = $('#gallery img').attr('width'); 

    if(imgwidth == 640) { 

    $('#content div#image').removeClass('large'); 

    $('#content img').removeClass('large'); 

    }else{ 

    $('#content div#image').addClass('large'); 

    $('#content img').addClass('large'); 

    } 
    return false; 
    }; 
}); 

任何帮助将不胜感激!

回答

0

我认为问题不在于你绑定事件的方式。

内,您的事件处理程序,例如做:

var imgwidth = $('#gallery img').attr('width'); 

这会给你的第一个图像(见attr文档)的宽度。

你如何确定用户与哪个图像进行交互?如果有焦点,那么你可以做例如

$('#gallery img').live("keydown", function(e) { 
    // here, 'this' is the DOM image object, and $(this) is the jQuery object for it 
    // ... 
}); 

......但重点是,您需要某种让计算机确定用户想要与哪个图像进行交互的方式。

+0

imgwidth部分只需要找到第一个图像。我在那里确定状态已经被切换或者没有,所以你可以按一次空格来放大#gallery中的图像,然后再去除放大它们的类。每当用户按下箭头键时,#gallery div将被新鲜图像替换。我在网上举了一个例子:http://werchris.com/emily。我在按键中还有其他关键事件,那么将live()设置为#gallery img可以解决问题吗? – 2010-10-12 16:38:28

+0

@Chris Anderson:你不应该有多个具有相同ID的元素(例如'id =“image”') – sje397 2010-10-12 23:06:34