2011-05-14 28 views
1

我使用Wordpress顯示縮略圖列表,當使用AJAX單擊時將加載頁面。我使用的是隱藏div來存儲特定縮略圖的頁面名稱,就像這樣:使用jquery/javascript選擇單擊元素的內容

<div class="load_image"> 
    <div class="image_path" style="display:none">portfolio-1</div> 
    <img src="..here is the thumbnail source" /> 
</div> 

這裏是AJAX代碼:

var ajax_load = "<img src='img/load.gif' alt='loading...' />"; 
    var loadUrl = "ajax/load.php"; 
    $(".load_image").click(function(){ 
      //Get the hidden-div-content from class image_path.....somehow 
     $("#ajax_result").html(ajax_load).load("<?php bloginfo('url') ?>/image_path"); 
    }); 

我將如何去獲得的內容點擊隱藏的div,以便我可以將它傳遞給AJAX調用?

回答

1

您可以使用this作爲元素的引用點擊,然後把它包在一個jQuery對象,並使用.children('.image_path')得到隱藏的DIV,然後.html()得到其內容。

$(".load_image").click(function(){ 
    var hidden_content = $(this).children('.image_path').html(); 
    $("#ajax_result").html(ajax_load).load("<?php bloginfo('url') ?>/image_path"); 
}); 

也許更好的是將數據存儲爲使用HTML5 data-屬性自定義屬性。

<div class="load_image" data-hidden="portfolio-1"> 
    <img src="..here is the thumbnail source" /> 
</div> 

然後用jQuery的.data()方法檢索數據。

var hidden_content = $(this).data('hidden'); 
0

有回調方法作爲參數:

$("#ajax_result").html(ajax_load).load("/image_path", function(val){ 
    //val contains what is returned 
    $('jquery_selector').html(val); 
});

看看jQuery的文檔here

0

你應該只使用鏈接和使用click事件攔截的默認行爲,然後執行你的AJAX呼叫。

<a href="/full-image.jpg" class="remote"><img src="/thumb-image.jpg"></a> 

然後......

$('a.remote').click(function(){ 
    $('#result').load($(this).find('img').attr('src').replace('thumb', 'full')); 
    return false; // prevent the browser from following the link 
}); 
0

在HTML文檔中,.html()可用於獲取任何元素的內容。如果選擇器表達式匹配多個元素,則只有第一個匹配項將返回其HTML內容。考慮以下代碼:

$('div.demo-container').html(); 

這是一個從jQuery文檔()文檔

http://api.jquery.com/html/