获取已淘汰的已点击元素的索引 [英] Get index of the clicked element in knockout
问题描述
获取无序列表的点击元素索引的最佳方法是什么?
What is the best way to get index of clicked element of an unordered list?
让我举个例子。假设我有以下HTML代码:
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>
现在我有以下javascript代码来获取索引:
Right now I have the following javascript code to get the index:
...
self.itemClicked = function(data, item) {
var index = $(item.target).index();
}
...
但问题是如果目标元素是< p>
,例如,我得到的结果不正确。那么我应该如何获得点击的< li>
元素的索引? knockout是否有一些方法,或者我应该以某种方式使用jquery?
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?
推荐答案
我建议使用Knockout的 $ index
上下文属性。请参阅下面的示例( JsFiddle ):
I recommend using Knockout's $index
context property. See example below (JsFiddle):
HTML
<!DOCTYPE html>
<html>
<body>
<ul data-bind="foreach: listItems">
<li data-bind="click: $parent.itemClicked.bind($data, $index())">
<p data-bind="text: title"></p>
</li>
</ul>
</body>
</html>
JavaScript
var vmodel = {
listItems: ko.observableArray([
{title: "Able"},
{title: "Baker"},
{title: "Charlie"}]),
itemClicked: function(index) {
alert(index);
}
};
ko.applyBindings(vmodel);
这篇关于获取已淘汰的已点击元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!