admin管理员组

文章数量:1429082

I use knockout here on a very basic example where I would like to pass the value of the clicked item to the function. I tried something which doesn't work. Does someone can show me how to proceed? Maybe I'm doint the wrong way?

Thanks for your help.

<div class='liveExample'>   
    <h2 data-bind="value: 'A', click: myFunction">Aaaaa</h2>  
    <h2 data-bind="value: 'B', click: myFunction">Bbbbb</h2>
    <h2 data-bind="value: 'C', click: myFunction">Ccccc</h2>
</div>

// Here's my data model
var ViewModel = function() {

    this.myFunction = function (elm)
    {
        alert('you clicked: ' + elm);
    }
};

ko.applyBindings(new ViewModel()); // This makes Knockout get to work

jsFiddle here: /

PS: I know we can do ...click: function () { myFunction('A'); }"> but I think there is a better way.

I use knockout here on a very basic example where I would like to pass the value of the clicked item to the function. I tried something which doesn't work. Does someone can show me how to proceed? Maybe I'm doint the wrong way?

Thanks for your help.

<div class='liveExample'>   
    <h2 data-bind="value: 'A', click: myFunction">Aaaaa</h2>  
    <h2 data-bind="value: 'B', click: myFunction">Bbbbb</h2>
    <h2 data-bind="value: 'C', click: myFunction">Ccccc</h2>
</div>

// Here's my data model
var ViewModel = function() {

    this.myFunction = function (elm)
    {
        alert('you clicked: ' + elm);
    }
};

ko.applyBindings(new ViewModel()); // This makes Knockout get to work

jsFiddle here: http://jsfiddle/LkqTU/10229/

PS: I know we can do ...click: function () { myFunction('A'); }"> but I think there is a better way.

Share Improve this question edited Jul 7, 2013 at 9:45 Sergey Berezovskiy 236k43 gold badges439 silver badges466 bronze badges asked Jul 7, 2013 at 9:23 BronzatoBronzato 9,39230 gold badges125 silver badges227 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

You can get value from event target (which is h2 element):

// Here's my data model
var ViewModel = function() {

    this.myFunction = function (data, event)
    {
        debugger;
        alert('you clicked: ' + event.target.value);
    }
};

ko.applyBindings(new ViewModel());

Read more on click binding

Try:

this.myFunction = function (vm, event)
    {
        alert('you clicked: ' + event.srcElement);
    }
this.myFunction = function (val1, val2)
{
    ...;
}

and in binding you must to set:

<h2 data-bind="value: 'C', click: myFunction.bind($data, 'A', 'B')">Ccccc</h2>

This must help you. You can pass any count of values by this method.

本文标签: javascriptPassing value to a function with knockoutStack Overflow