Get index of the clicked element

609 views
Skip to first unread message

levani

unread,
Nov 5, 2012, 11:49:12 AM11/5/12
to knock...@googlegroups.com
What is the best way to get index of clicked element of an unordered list? Lets say O have the following HTML code:

<ul data-bind="foreach: listItems">
    <li data-bind="click: itemClicked">
         <p data-bind="text: title"></p>
    </li>
</ul>

Right now I have the following javascript code to get the index:

...
self.itemClicked = function(data, item) {
    var index = $(item.target).index();
}
...

But the problem is the if the target element if <p> for example, I get incorrect result. So how should I get the index of the clicked <li> element? Does knockout have some method for this or I should use jquery in some way?

Florin Iacob

unread,
Nov 5, 2012, 4:53:22 PM11/5/12
to knock...@googlegroups.com
Try this:
<ul data-bind="foreach: listItems">
<li data-bind="click: function(data, event){ itemClicked(data, event, $index());}">
<p data-bind="text: title"></p>
</li>
</ul>
 
self.itemClicked = function(data, event, index) {
    alert(index);
}
 
You can define itemClicked function in the parent of listItems. In this case you can change te code like this:
 
<ul data-bind="foreach: listItems">
<li data-bind="click: function(data, event){ $parent.itemClicked(data, event, $index());}">
<p data-bind="text: title"></p>
</li>
</ul>
TheParentOfTheListItems.itemClicked = function(data, event, index) {
alert(index);
}
 
check this documentation page for all available options on the click binding.
Reply all
Reply to author
Forward
0 new messages