What is the best way to get index of clicked element of an unordered list?
Let me provide an example. Say I have the following HTML code:
<ul data-bind="foreach: listItems">
<li data-bind="click: $parent.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 is <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?
Instead of messing up your binding, it's much prettier getting the index inside the event function. You can get the binding context from the
event.target
, using theko.contextFor(element)
I recommend using Knockout's
$index
context property. See example below (JsFiddle):HTML
JavaScript