admin管理员组文章数量:1429082
I use knockout here on a very basic example where I would like to pass the value of the clicked item to the function. I tried something which doesn't work. Does someone can show me how to proceed? Maybe I'm doint the wrong way?
Thanks for your help.
<div class='liveExample'>
<h2 data-bind="value: 'A', click: myFunction">Aaaaa</h2>
<h2 data-bind="value: 'B', click: myFunction">Bbbbb</h2>
<h2 data-bind="value: 'C', click: myFunction">Ccccc</h2>
</div>
// Here's my data model
var ViewModel = function() {
this.myFunction = function (elm)
{
alert('you clicked: ' + elm);
}
};
ko.applyBindings(new ViewModel()); // This makes Knockout get to work
jsFiddle here: /
PS: I know we can do ...click: function () { myFunction('A'); }">
but I think there is a better way.
I use knockout here on a very basic example where I would like to pass the value of the clicked item to the function. I tried something which doesn't work. Does someone can show me how to proceed? Maybe I'm doint the wrong way?
Thanks for your help.
<div class='liveExample'>
<h2 data-bind="value: 'A', click: myFunction">Aaaaa</h2>
<h2 data-bind="value: 'B', click: myFunction">Bbbbb</h2>
<h2 data-bind="value: 'C', click: myFunction">Ccccc</h2>
</div>
// Here's my data model
var ViewModel = function() {
this.myFunction = function (elm)
{
alert('you clicked: ' + elm);
}
};
ko.applyBindings(new ViewModel()); // This makes Knockout get to work
jsFiddle here: http://jsfiddle/LkqTU/10229/
PS: I know we can do ...click: function () { myFunction('A'); }">
but I think there is a better way.
3 Answers
Reset to default 1You can get value from event target (which is h2
element):
// Here's my data model
var ViewModel = function() {
this.myFunction = function (data, event)
{
debugger;
alert('you clicked: ' + event.target.value);
}
};
ko.applyBindings(new ViewModel());
Read more on click binding
Try:
this.myFunction = function (vm, event)
{
alert('you clicked: ' + event.srcElement);
}
this.myFunction = function (val1, val2)
{
...;
}
and in binding you must to set:
<h2 data-bind="value: 'C', click: myFunction.bind($data, 'A', 'B')">Ccccc</h2>
This must help you. You can pass any count of values by this method.
本文标签: javascriptPassing value to a function with knockoutStack Overflow
版权声明:本文标题:javascript - Passing value to a function with knockout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745478067a2660053.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论