Knockout - Getting clicked element

2019-03-22 14:24发布

I have the following mark-up:

<fieldset>
   <div>
       <label class="editor-label">Question 1?</label>
       <input type="text" class="editor-field" />     
       <button type="button" data-bind="click: helpClicked">Help</button>
       <p class="help">Help 3</p>
   </div>
    <div>
       <label class="editor-label">Question 2?</label>
       <input type="text" class="editor-field" />
       <button type="button" data-bind="click: helpClicked">Help</button>
       <p class="help">Help 3</p>
   </div>
   <div>
       <label class="editor-label">Question 3?</label>
       <input type="text" class="editor-field" />
        <button type="button" data-bind="click: helpClicked">Help</button>
       <p class="help">Help 3</p>
   </div>
</fieldset>

I want to toggle the visibility of the the <p> with the class help in the same Div as the clicked button. I am trying to use $(this) to determine which button was clicked and then I could get the correct "help" element from there.

The problem is that $(this) isn't returning the clicked button.

At the moment I am trying to simply hide the clicked button like:

var viewModel = {
    helpClicked: function () {
        $(this).hide();           
    }
};

ko.applyBindings(viewModel);

This doesn't work. Can anyone help please?

4条回答
可以哭但决不认输i
2楼-- · 2019-03-22 14:53

Try using event.currentTarget followed by next()

$(event.currentTarget).next().hide();   

Working example here

查看更多
仙女界的扛把子
3楼-- · 2019-03-22 14:53

Are those divs inside the fieldset built via Knockout? (they look templatey). If so, I think a more MVVMish way to approach this would be to extract the currently bound item from the button click handler and bind the visibility of each help paragraph to a view model property set by that handler on the corresponding item, rather than doing the UI operations procedurally. At least, this is the pattern I've been moving towards and finding it much nicer (especially after doing similar things in WPF and Silverlight).

查看更多
在下西门庆
4楼-- · 2019-03-22 14:53
This should work

var viewModel = 
{
         helpClicked: function (data,element) {
       /*
      data is the current model passed to the button
      element is the button currently interacting with
     but to get the dom object equivalent of the 
     element you've to access it          
    via its currentTarget property
    */
        $(element.currentTarget).hide();           
    }
};

ko.applyBindings(viewModel);
查看更多
萌系小妹纸
5楼-- · 2019-03-22 15:03

Here is a jsFiddle with one possible solution:

http://jsfiddle.net/unklefolk/399MF/1/

You can target the DOM elements you want via this syntax:

var viewModel = {     
    helpClicked: function (item, event) {   
        $(event.target).hide(); 
        $(event.target).next(".help").show()            
    } 
};  
ko.applyBindings(viewModel); ​
查看更多
登录 后发表回答