Passing parameter using onclick or a click binding with KnockoutJS(使用 onclick 传递参数或使用 KnockoutJS 进行点击绑定)
问题描述
我有这个功能:
函数make(place){place.innerHTML = "东西"}
我以前用纯 JavaScript 和 html 来做这个:
<button onclick="make(this.parent)">点击我</button>
如何使用惯用的 knockout.js 做到这一点?
如果您在 Knockout 中设置了点击绑定,则事件将作为第二个参数传递.您可以使用该事件来获取发生点击的元素并执行您想要的任何操作.
这是一个演示:http://jsfiddle.net/jearles/xSKyR/
或者,您可以创建自己的自定义绑定,它将接收绑定到的元素作为第一个参数.在初始化时,您可以附加自己的点击事件处理程序来执行您希望执行的任何操作.
http://knockoutjs.com/documentation/custom-bindings.html
HTML
<button data-bind="click: clickMe">点击我!</button></div>Js
var ViewModel = function() {变种自我=这个;self.clickMe = 函数(数据,事件){var 目标 = event.target ||事件.srcElement;if (target.nodeType == 3)//消除 Safari 错误目标=目标.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 进行点击绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 onclick 传递参数或使用 KnockoutJS 进行点击绑


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06