Knockout does not recognize manually click

浪子不回头ぞ 提交于 2019-12-14 04:25:49

问题


Here is sample http://jsfiddle.net/HhXGH/57/

I am clicking radio button by jquery but knockout.js does not recognize it.Still it shows first clicked value.

<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
    Preferred flavor of spam:
    <div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
    <div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
    <div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>


var viewModel = {
        wantsSpam: ko.observable(true),
        spamFlavor: ko.observable('cherry')
    };

ko.applyBindings(viewModel);

$(':radio:last').click();

alert(viewModel.spamFlavor())

回答1:


This because Knockout is subscribing to the click events of checked radio/checkbox elements only. If you checkout the binding handler code for checked. It does this.

var updateHandler = function() {
            var valueToWrite;
            if (element.type == "checkbox") {
                valueToWrite = element.checked;
            } else if ((element.type == "radio") && (element.checked)) {
                valueToWrite = element.value;
            } else {
                return; // "checked" binding only 
                responds to checkboxes and selected radio buttons
            }

So in order to get your code to work do this.

$(':radio:last').prop('checked', true).click();

However if the goal is to check the last value, why not just do

viewModel.spamFlavor("msg");

This would achieve the same result.

Hope this helps.




回答2:


Adding $(':radio:last').attr('checked', true); in addition to triggering click makes it work for me:

http://jsfiddle.net/jearles/HhXGH/61/




回答3:


I have two different jsFiddles since I'm not sure exactly what your after.

The first jsFiddle will respond via alert when the last radio button is manually clicked.

The second jsFiddle is your posted /57/ jsFiddle without the alert.

Using an alert or console.log with a function will actually invoke that function. That said, after you have manually set the .click() to the last radio button, it's inadvertently reset back to cherry since that's the default value.

RE-EDIT: The second jsFiddle now includes alert written in syntax that doesn't invoke the function & now uses shorted markup.



来源:https://stackoverflow.com/questions/10769114/knockout-does-not-recognize-manually-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!