简体   繁体   English

如果父项具有onclick绑定,则复选框单击忽略

[英]checkbox click ignored if parent has onclick bind

Click on a checkbox is ignored if the parents "onclick" event is binded to a function. 如果父级“ onclick”事件绑定到函数,则忽略复选框的单击。 I don't want this to happen: how can I do it? 我不希望这种情况发生:我该怎么办? I've stripped down my code to illustrate the problem. 我已经精简了代码以说明问题。

HTML: HTML:

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

JS: 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. 删除对容器div的someFunction的调用会导致预期的行为。 See example: here . 参见示例: 此处 Obviously, this is not solving the problem as I need someFunction to be called as well. 显然,这并不能解决问题,因为我也需要someFunction


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. 为了使用调试器遵循此链,我在复选框上绑定了click事件。

<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). 随意打开您的开发工具,看看当我们处于startDebug函数中时,如何实现预期的行为(但稍后会恢复为错误的状态)。 Fiddle with debugger call: here . 调试器调用的小提琴: 这里

You just need to return true from your click handler to trigger the browser's default click action: 您只需要从click处理程序返回true即可触发浏览器的默认点击操作:

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

Demo JSFiddle . 演示JSFiddle

See also in the documentation: Allowing the default click action (probably the next note Preventing the event from bubbling will be also relevant) 另请参见文档中的内容: 允许默认的click操作 (可能与下一个注意事项有关: 防止事件冒泡也很重要)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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