2012-07-31 64 views
0

我怎樣才能得到一個<div>內容的內容時,點擊一個鏈接jQuery來得到一個div

如:

有兩個div標籤

<div id="1" > This Is First Div </div> 
<div id="2" > This Is Second Div </div> 
<a href="#" id="click" >Click Here</a> 

當鏈接點擊,我需要得到的內容如下:

這是拳頭Div
這是第二個div

回答

3

如果我很好理解

$('a').on('click', function(ev) { 
    ev.preventDefault(); 
    $($(this).prevAll('div').get().reverse()).each(function() { 
    alert ($(this).text()) 
    }) 
}); 

一點題外話,在id屬性選擇是無效的(他們不能以數字開頭)

例小提琴: http://jsfiddle.net/533qX/

編輯。隨着一個單一的警報

$('a').on('click', function(ev) { 
    var text = ""; 
    ev.preventDefault(); 
    $($(this).prevAll('div').get().reverse()).each(function() { 
    text += $(this).text() + "\n"; 
    }) 
    alert(text); 
}); 
+0

喜其不工作u能請給我的jsfiddle – 2012-07-31 12:44:39

+0

一個演示中,我需要定義腳本中的DIV ID,我需要獲得所有在一個警報是可能的 – 2012-07-31 12:49:17

3
function alertDiv(divId){ 
    $('#click').on('click', function(e){ 
     alert ($(divId).text()); 
     e.preventDefault(); 
    }); 
} 

alertDiv('#one'); 
alertDiv('#two'); 

http://jsbin.com/ebowim/2/edit

+0

主要帖子鏈接是這個http://stackoverflow.com/questions/11734448/a-button-to-add-a-product-to-a-cart我需要一個按鈕來添加該產品到購物車你可以幫助我嗎? – 2012-07-31 12:52:56