最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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 pletely as the project I am working in is already using knockout nearly exclusively. Any ideas?

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 pletely as the project I am working in is already using knockout nearly exclusively. Any ideas?

Share Improve this question asked Nov 25, 2014 at 2:13 marked-downmarked-down 10.4k22 gold badges93 silver badges153 bronze badges 2
  • 1 Please don't use jQuery in your KO viewmodels! You should use the observables and the checked binding instead to track when the checkbox is selected: jsfiddle/eqoryb6v – nemesv Commented Nov 25, 2014 at 6:23
  • @nemesv, okay, that's helpful, but I have multiple rows, each with one checkbox. Using your method, when I select one checkbox, all the rows and checkboxes are highlighted. jsfiddle/eqoryb6v/1 – marked-down Commented Nov 25, 2014 at 19:30
Add a ment  | 

1 Answer 1

Reset to default 16

You should be able to acplish 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 ment 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>
发布评论

评论列表(0)

  1. 暂无评论