[英]How to reveal dynamic data on click with jquery
編輯 : 這是一個較好的方法,因為在實現時所提供的答案可能有錯誤a
標簽,或者img
標簽。
================================================== ==============
我正在從API調用博客數據。 (我已按月將數據重新格式化為數組)。
到目前為止,博客標題會打印到網頁上。 我希望用戶能夠單擊標題並顯示其描述。
到目前為止,這是我的一些代碼:
var blogPosts = $('#blog-posts');
$.each(byMonth, function(key, value) {
var outer = byMonth[key]
$.each(outer, function(k, v) {
var inner = outer[k]
var monthBlogPosts = $('<div class = "month"> </div>').appendTo(blogPosts);
$.each(inner, function(i, obj) {
title = inner[i].Title
description = inner[i].Description
date = inner[i].DatePublished
$('<div class = "title-list"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
// if a title is clicked, show its Description
showDescription(description);
})
})
});
function showDescription(d){
$('.unique-title').on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
單擊標題時,將打印所有描述,而不是匹配的描述。 我知道這是因為我在嵌套循環中調用了該函數,但是在調用它之外的描述變量時也遇到了麻煩。
我也嘗試過
showDescription(title, description)
//...
function showDescription(t, d){
$(title).on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
但是沒有任何內容打印到html頁面。
本質上,我想獲取標題索引,並在單擊它時打印其各自的描述。
那么好吧。 據我所能理解的(通過查看您的代碼)。 你不能注冊用簡單的一個事件on
的動態添加元素。 您必須使用委托。
嘗試這個
1)刪除函數調用(在循環內)
2)刪除整個函數showDescription
並添加事件,如下所示:
$('#blog-posts').on('click', '.unique-title',function(){
alert('title clicked').
});
3)至於顯示描述,我認為最好的方法是將描述添加到div中並將其隱藏。 單擊標題后,稍后顯示。
(inside the loop)
$('<div class = "desc" style="display:none">' + description + '</div>').appendTo(monthBlogPosts);
然后在上面的#2。 替換為此。
$('#blog-posts').on('click', '.unique-title',function(){
$(this).next('.desc').show(); //I am assuming desc will be next to the clicked title here. You can modify it as needed.
});
最后,這只是代碼的概述,因此可能無法按預期工作,但是我很確定這應該可以給您一個思路並幫助您入門。
您應該使用事件委托將click事件附加到文檔,當.title-list
作為事件目標時,該事件會冒泡並觸發。
$(document).on('click', '.title-list', function(event) {
showDescription(event.currentTarget) // pass the element being clicked (we will need it later)
})
您還需要修改獲取描述的方式。 您可以將描述存儲在.title-list
的數據屬性中, .title-list
所示:
$('<div class = "title-list" data-description="'+ description +'"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
所以您現在可以修改showDescription()
以便從我們傳遞給函數的元素中獲取數據
function showDescription(element){
var d = $(element).data('description')
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.