使用 onclick 或使用 KnockoutJS 的单击绑定传递参数 [英] Passing parameter using onclick or a click binding with KnockoutJS
问题描述
我有这个功能:
function make(place){place.innerHTML = "东西"}
我曾经用普通的 JavaScript 和 html 来做到这一点:
我如何使用惯用的knockout.js 来做到这一点?
如果您在 Knockout 中设置了单击绑定,则该事件将作为第二个参数传递.您可以使用该事件获取发生点击的元素并执行您想要的任何操作.
这是一个演示:http://jsfiddle.net/jearles/xSKyR/
或者,您可以创建自己的自定义绑定,它将接收绑定到的元素作为第一个参数.在初始化时,您可以附加自己的点击事件处理程序来执行您希望的任何操作.
http://knockoutjs.com/documentation/custom-bindings.html
HTML
<button data-bind="click: clickMe">点击我!</button>
Js
var ViewModel = function() {var self = this;self.clickMe = 函数(数据,事件){var target = event.target ||event.srcElement;if (target.nodeType == 3)//打败 Safari 错误目标 = target.parentNode;target.parentNode.innerHTML = "东西";}}ko.applyBindings(new ViewModel());
I have this function:
function make(place)
{
place.innerHTML = "somthing"
}
I used to do this with plain JavaScript and html:
<button onclick="make(this.parent)">click me</button>
How can I do this using idiomatic knockout.js?
If you set up a click binding in Knockout the event is passed as the second parameter. You can use the event to obtain the element that the click occurred on and perform whatever action you want.
Here is a fiddle that demonstrates: http://jsfiddle.net/jearles/xSKyR/
Alternatively, you could create your own custom binding, which will receive the element it is bound to as the first parameter. On init you could attach your own click event handler to do any actions you wish.
http://knockoutjs.com/documentation/custom-bindings.html
HTML
<div>
<button data-bind="click: clickMe">Click Me!</button>
</div>
Js
var ViewModel = function() {
var self = this;
self.clickMe = function(data,event) {
var target = event.target || event.srcElement;
if (target.nodeType == 3) // defeat Safari bug
target = target.parentNode;
target.parentNode.innerHTML = "something";
}
}
ko.applyBindings(new ViewModel());
这篇关于使用 onclick 或使用 KnockoutJS 的单击绑定传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!