简体   繁体   中英

checkbox click ignored if parent has onclick bind

Click on a checkbox is ignored if the parents "onclick" event is binded to a function. I don't want this to happen: how can I do it? I've stripped down my code to illustrate the problem.

HTML:

<div class="container" data-bind="click: someFunction">
   Click me: <input type="checkbox" data-bind="checked: selected" />
</div>

JS:

function vm() {
    this.selected = ko.observable(true);
    this.someFunction = function(){};
}
ko.applyBindings(new vm());

Fiddle: here . Try to click on the checkbox: it seems like nothing happens (not true: I'll explain later what happens).

Removing the call to someFunction to the container div result in the expected behaviour. See example: here . Obviously, this is not solving the problem as I need someFunction to be called as well.


I've followed the code with a debugger and noticed how the click is not actually ignored but a long chain of events happens the last one of which is reverting the value of the checkbox (thus, invalidating the click).

To follow this chain using the debugger, I've binded a click event on the checkbox.

<div class="container">
    Click me: <input type="checkbox" data-bind="click: startDebug, checked: selected" />
</div>

Feel free to open your dev tools and see how the expected behaviour is achieved while we're inside of the startDebug function (but reverted to the wrong one later on). Fiddle with debugger call: here .

You just need to return true from your click handler to trigger the browser's default click action:

function vm() {
    this.selected = ko.observable(true);
    this.someFunction = function(){ return true; };
}

Demo JSFiddle .

See also in the documentation: Allowing the default click action (probably the next note Preventing the event from bubbling will be also relevant)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM