2011-12-30 107 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/