2011-12-07 47 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(); 
});