2011-12-30 194 views
1

如果您单击this page上的单元格,它将加载图像的较大版本。我试图达到同样的效果。jQuery:获取内容/ innerhtml onclick

我迄今为止得到:http://jsfiddle.net/8mYW9/

首先,我知道具有"appear" <div>是多余的 - 是否有利用$(this)appendTo();,而不是一个好办法?

最终我的想法是抓住div中包含的锚点的id,并将其添加到单元格中。我该怎么做...?

回答

1

$(document).ready(function() { 
    $('#appear').hide(); 
    $('.links').click(function() { 
     var $this = $(this);//cache the $(this) selector since it will be used more than once 
     $this.children('.appear').html('item id: ' + $this.children('a').attr('id')).fadeToggle('slow'); 
    }); 
}); 

演示:http://jsfiddle.net/8mYW9/7/

你有重复的ID顺便说一句,在HTML文档中不能有多个具有相同ID的元素。

1

你可以做到这一点与:

$(document).ready(function() { 
    $('#appear').hide(); 
    $('.links').click(function() { 
     $(this).append('<div>' + $(this).find('a:first').attr('id') + '</div>'); 
    }); 
}); 

JS Fiddle demo

修正,使得只有一个id被示出(其它显示最新之前被移除):

$(document).ready(function() { 
    $('#appear').hide(); 
    $('.links').click(function() { 
     $(this).closest('.container').find('.appended').remove(); 
     $(this).append('<div class="appended">' + $(this).find('a:first').attr('id') + '</div>'); 
    }); 
}); 

JS Fiddle demo

顺便说一句,它逃过我在第一时间通知,但有多个元素共享相同id你已经无效的(X)HTML:一个id必须是文档(引文:W3.org)内独特。

参考文献:

0

请尝试使用类选择器。如果您更改ID属性类的appear元素,你可以做到这一点

$(document).ready(function() { 
    $('.appear').hide(); 
    $('.links').click(function() { 
     $(this).find(".appear").fadeToggle('slow', function() { 
      $(this).html('item id:') 
     }); 
    }); 
}); 

http://jsfiddle.net/8mYW9/