我似乎不明白我在这里做错了什么。
在某种程度上,我的代码确实有效,但是它没有找到单击元素的id,而是找到了所有id的
http://jsfiddle.net/34a5b/ -我把它放到动画中,这样你就可以看到它找到了#item1,然后找到了#item2
我要寻找的基本功能如下:
当单击li时,
>查找特定id >对应于特定id的功能
对为什么这不起作用有什么想法吗?
var $Nav= $('#Nav');
var $Boxee= $('#BoxeeBox');
$Nav.each(function(){
$(this).find('li').click(function() {
if( $(this).find('#item1') ){
$Boxee.animate({ backgroundColor:'blue' });
}
if( $(this).find('#item2') ){
$Boxee.animate({ backgroundColor:'red' });
}
});
});现在我想知道为什么我把$nav.each..。
我也试着想出更有活力、更简单的方法来做这样的事情,但我想不出。惊喜惊喜..。如果有人也能指点我的方向,我会很感激的(尽管我仍然想知道为什么我的代码不能工作)。
发布于 2011-07-31 02:47:46
您不必通过$Nav循环。jQuery单击将绑定到所有li (如果您说$('#Nav li').click(...) )
代码不能工作的原因是:$(this).find('#item1') --在这里,$(this)的意思是li,所以您需要在其内部键入#item1。
固定:http://jsfiddle.net/34a5b/1/
var $Nav = $('#Nav li');
var $Boxee = $('#BoxeeBox');
$Nav.click(function() {
if (this.id == 'item1') {
$Boxee.animate({
backgroundColor: 'blue'
});
}
if (this.id == 'item2') {
$Boxee.animate({
backgroundColor: 'red'
});
}
});稍微好一点的(性能)版本是使用.delegate ( http://jsfiddle.net/34a5b/9/ ):
$('#Nav').delegate('li', 'click', function() {
if (this.id == 'item1') {
$Boxee.animate({
backgroundColor: 'blue'
});
}
if (this.id == 'item2') {
$Boxee.animate({
backgroundColor: 'red'
});
}
});发布于 2011-07-31 02:58:24
不知道你为什么要使用每个函数。下面的代码可以
var $Nav= $('#Nav');
var $Boxee= $('#BoxeeBox');
$('#Nav li').click(function() {
if( $(this).attr('id') == 'item1' ){
$Boxee.animate({ backgroundColor:'blue' });
}
else if($(this).attr('id') == 'item2') {
$Boxee.animate({ backgroundColor:'red' });
}
});在http://jsfiddle.net/34a5b/10/检查Fiddle
https://stackoverflow.com/questions/6887224
复制相似问题