How can I pass the current element to a Javascript function in a Knockout.js binding?

╄→гoц情女王★ 提交于 2019-12-21 12:39:41

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/27117681/how-can-i-pass-the-current-element-to-a-javascript-function-in-a-knockout-js-bin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!