如何将当前元素传递给Knockout.js绑定中的Javascript函数? [英] How can I pass the current element to a Javascript function in a Knockout.js binding?

查看:95
本文介绍了如何将当前元素传递给Knockout.js绑定中的Javascript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图根据是否选中子复选框将一个类添加到使用Knockout.js的元素中。为此,我试图将这个作为参数传递给我的函数。目前,我的删节DOM结构如下:

 < tr data-bind =css:{selected:isRowChecked(this )}> 
< td>< label>< input type =checkbox>< / label>< / td>
< / tr>

我的 isRowChecked 函数是this使用jQuery来定位输入):

$ p $ 函数isRowChecked(elem){
var checkbox = $(elem ).find( '输入[类型= 复选框]');
return checkbox.checked;

然而,如果我 console.log elem 我得到的全部是全局窗口对象。

使用jQuery完全解决这个问题是不可行的,因为我工作的项目已经几乎完全使用knockout。任何想法?

解决方案

您应该可以通过传递特殊绑定上下文变量$ element来完成此任务。这是在这里讨论的最后一个变量。


$ element

这是元素DOM对象(对于虚拟元素,它将是
注释DOM对象)目前的约束力。如果
绑定需要访问当前元素的属性,这可能很有用。示例:

< div id =item1data-bind =text:$ element.id >< / div>



您的情况如下所示:

 < tr data-bind =css:{selected:isRowChecked($ element)}> 
< td>< label>< input type =checkbox>< / label>< / td>
< / tr>


So I'm trying to add a class to an element using Knockout.js based on whether a child checkbox is checked or not. To do so, I'm trying to pass this as an argument to my function. Currently, my abridged DOM structure is the following:

<tr data-bind="css: { selected: isRowChecked(this) }">
    <td><label><input type="checkbox"></label></td>
</tr>

An my isRowChecked function is this (I'm using jQuery to locate the input):

function isRowChecked(elem) {
    var checkbox = $(elem).find('input[type="checkbox"]');
    return checkbox.checked;
}

Yet, if I console.log elem all I get is the global window object.

It is not feasible to use jQuery to solve this problem completely as the project I am working in is already using knockout nearly exclusively. Any ideas?

解决方案

You should be able to accomplish this by passing the special binding context variable $element. It's the last variable discussed here.

$element

This is the element DOM object (for virtual elements, it will be the comment DOM object) of the current binding. This can be useful if a binding needs to access an attribute of the current element. Example:

<div id="item1" data-bind="text: $element.id"></div>

In your case, that would look like this:

<tr data-bind="css: { selected: isRowChecked($element) }">
    <td><label><input type="checkbox"></label></td>
</tr>

这篇关于如何将当前元素传递给Knockout.js绑定中的Javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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