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

查看:378
本文介绍了使用onclick或与KnockoutJS的点击绑定传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 函数make(place)
{
place.innerHTML = somthing
}

我用普通的JavaScript和html来做这件事: >点击我>< / button>按钮onclick =make(this.parent)>点击我< / button>

如何使用惯用的knockout.js来做到这一点?

解决方案

如果您在Knockout中设置了点击绑定,则该事件将作为第二个参数传递。您可以使用该事件来获取发生点击的元素,并执行任何您想要的操作。



下面是一个演示: http://jsfiddle.net/jearles/xSKyR/

或者,你可以创建自己的自定义绑定,它将接收绑定的元素作为第一个参数。在init中,您可以附加自己的单击事件处理程序来执行任何您希望执行的操作。



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 =函数(数据,事件){

var target = event.target || event.srcElement;

if(target.nodeType == 3)//击败Safari bug
target = target.parentNode;

target.parentNode.innerHTML =something;
}
}

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天全站免登陆