javascript 在淘汰赛中获取被点击元素的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13237058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get index of the clicked element in knockout
提问by King Julien
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:
让我举一个例子。假设我有以下 HTML 代码:
<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:
现在我有以下 javascript 代码来获取索引:
...
...
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?
但问题是,如果目标元素是<p>
例如,我得到的结果不正确。那么我应该如何获取被点击<li>
元素的索引呢?淘汰赛对此有一些方法还是我应该以某种方式使用jquery?
回答by Joseph Sturtevant
I recommend using Knockout's $index
context property. See example below (JsFiddle):
我建议使用 Knockout 的$index
上下文属性。请参阅下面的示例(JsFiddle):
HTML
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
JavaScript
var vmodel = {
listItems: ko.observableArray([
{title: "Able"},
{title: "Baker"},
{title: "Charlie"}]),
itemClicked: function(index) {
alert(index);
}
};
ko.applyBindings(vmodel);?
回答by Oleg Grishko
Instead of messing up your binding, it's much prettier getting the index inside the event function. You can get the binding contextfrom the event.target
, using the ko.contextFor(element)
与其弄乱您的绑定,不如在事件函数中获取索引更漂亮。你可以得到绑定上下文从event.target
使用ko.contextFor(element)
self.click = function (data, event) {
var context = ko.contextFor(event.target);
console.log(context.$index());
};