通过jquery选择动态id为div的Childs

时间:2012-08-17 00:49:59

标签: jquery jquery-selectors

看看这些家伙:

<div id="Item_23">
 <div class="Info">
   <a class="Link" href="#" onclick="call(23)">Link</a>
   <div class="text">
     <a class="cancel" href="cancel.asp">Cancel</a>
   </div>
 </div>
</div>

父div具有动态ID,其数字部分是可变的 现在,我想在一个函数中按类选择这个孩子中的一个。怎么办?

function call(e)
    // Selecting a.cancel
end function

2 个答案:

答案 0 :(得分:0)

也许类似

$('div[id^=Item_] div.text');

$('div[id^=Item_] a.Link');

回复您的修改

试试这个

function call(e) {

    // Find the inner anchor
    var theAnchor = $('div[id=Item_' + e + '] div.text').find('a.cancel');
}

您在调用或jQuery代码中缺少下划线,因此它正在寻找具有ID的div

Item23

而不是ID

Item_23

<击>

这是一个JSFiddle,演示了在单击其他链接时获取取消链接。

http://jsfiddle.net/PyDKg/14/

正如@undefined建议的那样,你不需要内联的javascript调用,因为你正在使用jQuery。我稍微更改了函数,因此它只获取父项的ID并将整个ID作为参数发送。

<强> HTML

<div id="Item_23">
    <div class="Info">
        <a class="Link" href="#">Link</a>
        <div class="text">
            <a class="cancel" href="cancel.asp" data-val="Yay got it!">Cancel</a>
        </div>
    </div>
</div>

<强> JS

$(document).ready(function(){
    $('a.Link').click(function(){
        var id = $(this).parents('div[id^=Item_]').attr('id');
        callAnchor(id);
    });
});

function callAnchor(e) {

    // Find the inner anchor
    var theAnchor = $('div[id=' + e + '] div.Info div.text').find('a.cancel');

    // Print the data-val attribute to prove that it was found.
    alert($(theAnchor).attr('data-val'));
}

答案 1 :(得分:-1)

首先,修复原始选择器,如下所示:

 var item = $('div[id=Item_' + e + '] div');

有很多方法可以选择子元素,包括childrennext,但这是最简单的,最不可能突破标记更改:

item.find('.Link');