2011-12-07 55 views
0

我試圖找到類名「鏈接」跨度的文本,但我有問題。使用ID作爲變量

<div id="item-0" class="box"> 
    ....... 
</div> 
<div id="item-1" class="box"> 
    <p><strong>Link: </strong><span class="link">http://www.domain.com/list44/</span></p> 
    <p><input type="submit" value="submit" class="load-button2"></p> 
</div> 
<div id="item-2" class="box"> 
    ....... 
</div> 


$(".load-button2").click(function(){ 
    var id = $(this).closest('.box').attr('id'); 
    alert(id); // showing the right box ID 
    var linkp = $(/*** what should i put here? ***/ "#" + id + " .link").text; 
}); 
+3

*什麼*的問題到底是什麼? –

+0

'var linkp = $(「#」+ id +「.link」)。text();' –

回答

4

你應該只能夠做到:

$(".load-button2").click(function(){ 
    var id = $(this).closest('.box').attr('id'); 
    alert(id); // showing the right box ID 
    var linkp = $("#" + id).find(".link").text(); 
}); 

雖然,一個更優雅的解決辦法是:

$(".load-button2").click(function(){ 
    var linkp = $(this).closest('.box').find(".link").text(); 
}); 
+1

'$(this).closest('.box')。find('.link')。文字()'?似乎沒有任何需要重新定位盒子。 – Pointy

+0

哈哈,是啊,我只是更新說:) – danwellman

+0

@Pointy:剛注意到我的回答和你的評論完全一樣(並且間隔2秒)。 – Blender

1
$(".load-button2").click(function(){ 
    var id = $(this).closest('.box').attr('id'); 
    alert(id); // showing the right box ID 
    //var linkp = $(what should i put here/"#" + id = " .link").text; 
    var linkp = $("#"+id).find(".link").text; 
}); 
1

的替代,所以你不必做另一個完整的DOM遍歷(因爲你已經獲得了容器)。

$(".load-button2").click(function(){ 
    var container = $(this).closest('.box'); 
    var id = container.attr('id'); 
    alert(id); // showing the right box ID 
    var linkp = container.find('.link').text(); 
    alert(linkp); 
}); 

See it in action

+0

另一種解決方法。謝謝! –

4

你可以試試這個代碼:

$(".load-button2").click(function(){ 
    var text = $(this).closest('.box').find('.link').text(); 
});