2009-08-02 99 views
0
導航DOM

我有下面的代碼出現在HTML頁面中多次(文字值不同):麻煩的jQuery

<div> 
<a href="1.html"> 
    <span class="e"> 
    <span class="1">stuff1</span> 
    <span class="2">stuff2</span> 
    <span class="3">stuff3</span> 
    </span> 
</a> 
<a class="click" href="2.html">link</a> 
</div> 

什麼,我試圖做的是點擊鏈接「鏈接」時, ,產生一個包含stuff1,stuff2和stuff3值的對話框。我實際上遇到了跨度值的問題。實際上,我想要的是獲取$(this)並獲取它的文本,它只是跨越孩子的跨度兒童。

謝謝! -Mala

回答

3

我有一個小麻煩搞清楚你的​​意思,但也許這就是它:

$('.click').click(function() { 
    // using our parent as a base, look for any class='e' element, and get its children. 
    var $collection = $('.e > *', $(this).parent()); 
    var text = []; 
    $collection.each(function() { 
    // add the text within each span to an array 
    text.push($(this).text()); 
    }); 

    // show the text of the spans as a comma separated list 
    alert(text.join(', ')); 


}); 

一個jQuery對象上的.text()函數將返回的內文跨度(或任何其他元素)。

迴應評論:

$('.e span', $(this).parent())會工作爲好,.e > *選擇class='e'元素的所有直接子。 $函數的第二個參數用作範圍;它只能找到該基本元素下的元素。

也可以寫成$(this).parent().find('span span')。僅僅搜索「跨度」的危險是它也會匹配外部跨度 - 外部跨度$('.e', $(this).parent()).text()會將所有3個元素的文本一起返回 - 這實際上可能是您想要的。

+0

感謝您的回覆! 問題出現在頁面上多次出現,我只希望它發生在點擊鏈接的div中,所以它需要以某種方式合併鼠標點擊的$(this)並從那裏相對移動... – Mala 2009-08-02 23:46:06

1
$(this).prev().children(".e").get(0).children() 

會讓你以前的兄弟姐妹的第一個孩子的類「e」的所有孩子。你也可以在沒有jQuery的情況下做到這一點,但這有點醜陋;如果你有一個你感興趣的節點的引用,你正在尋找它的.previousSibling.getElementsByTagName('span')[0].childNodes - 這是一個數組。