通过选中复选框获取特定的子元素ID

时间:2016-10-25 18:35:51

标签: javascript jquery knockout.js

我使用Knockout js进行绑定,我想获取子元素ID,当我选中复选框时,我的父ID是由唯一ID生成的,如何实现这个

//this div is inside the for each loop

<div data-bind="attr: { id: 'unique_' + $index()},fav:  ({item:someItem})" class="Tab">

 // i need to get this itemIDs when i selecte the check box
   <div id=randon_item1><div>
   <div id=random_item2><div>
   <div id=random_item3><div>
   <div id=random_item4><div>
   </div>
    <input id="ckh1" type="checkbox" data-bind="value:userId(), click:      $root.toggleAssociation" />


 //toggleAssociation//
 self.toggleAssociation = function (item, event) {
 here i am getting the item and all parent div with unique_0 ID which will   be incremented for others div
 how i can get child element ID which is generated randomly
 }

1 个答案:

答案 0 :(得分:0)

我对knockout.js不熟悉,但是您的子元素ID属性中似乎有一些拼写错误,您可能希望在父div中包含该复选框,其类为&#34; Tab&# 34;像这样:

<div data-bind="attr: { id: 'unique_' + $index()}, fav: ({item:someItem})" class="Tab">

    <div id="random_item1"></div>
    <div id="random_item2"></div>
    <div id="random_item3"></div>
    <div id="random_item3"></div>

    <input id="chk1" type="checkbox" data-bind="value:userId(), click: $root.toggleAssociation" />

</div>

然后你的功能:

self.toggleAssociation = function (item, event) {
    alert(event.target.parentNode.id);
}

或jQuery:

self.toggleAssociation = function (item, event) {
    alert($(event).parent().attr(id));
}

如果你想要每一个&#34; random_item&#34; id&#39;然后你可以在你的self.toggleAssociation函数中迭代它们:

$(event).siblings('div').each(function(){
    alert($(this).attr('id'));
});