如何通过jQuery中的chidren数据获取父ID?

时间:2011-09-15 10:04:55

标签: javascript jquery

我吹HTML,我想编写一个函数,可以通过其子记录和记录索引获取锚标记的id。它应该是这样的:

getLinkId("100", 0)=300001
getLinkId("RD", 1)=300001
getLinkId("PD", 1)=300002
getLinkId("902", 2)=300002

我认为jQuery可能有助于实现,但我对它并不熟悉。有谁可以帮助我?

<ul id="listview_Sample">
    <li role="option">
    <div class="ui-btn-inner ui-li">
    <div class="ui-btn-text"><a href="" class="listviewLines" id="300001">
    <div class="lv_lines" id="300001">
    <div class="lv_line">
    <div class="lv_line_field">100</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">RD</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">501</div>
    </div>
    </div>
    </a></div>
    </li>
    <li role="option">
    <div class="ui-btn-inner ui-li">
    <div class="ui-btn-text"><a href="" class="listviewLines" id="300002">
    <div class="lv_lines" id="300002">
    <div class="lv_line">
    <div class="lv_line_field">200</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">PD</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">902</div>
    </div>
    </div>
    </a></div>
    <span class="ui-icon ui-icon-arrow-r"></span></div>
    </li>

2 个答案:

答案 0 :(得分:2)

此功能符合您对此特定情况的要求。请参阅注释以获取每行的说明:

function getLinkId(id, col){
    var main = document.getElementById("listview_Sample");

    //enumerate through all list items
    for(var i=0,len=main.getElementsByTagName("li").length; i<len; i++){

        //Each list item contains 3 .lv_line_field elements.
        // Compare the content of the (i*3+col)th element.
        if(main.getElementByClassName("lv_line_field")[i*3+col].textContent == id){

            //match found, return id.
            return document.getElementsByClassName("listviewLines")[i].id;
        }
    }
}

答案 1 :(得分:2)

我认为这应该有用。

function getLinkId(id, index){
    var matchedResult = $('div.lv_line_field:contains("' + id + '")');

    if (matchedResult.parent().index() == index)
        return matchedResult.closest('a.listviewLines').attr('id');

    return null;
}

http://jsfiddle.net/4KezR/

甚至可以在一行中完成所有操作:

function getLinkId(id, index){
    return $('div.lv_line_field:contains("' + id + '")').filter(function() {
        return $(this).parent().index() == index;
    }).closest('a.listviewLines').attr('id');
}