使用 onclick 传递参数或使用 KnockoutJS 进行点击绑定 [英] Passing parameter using onclick or a click binding with KnockoutJS

查看:20
本文介绍了使用 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 进行点击绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆