简体   繁体   中英

knockoutjs button click event doesn't fire

I'm building HTML from data which is returned from ajax, it's looking good when I view the source, but for some reason the click event doesn't fire.

This is how I'm creating the markup:

$.ajax({
                    type: "POST",
                    url: "/webservices/WebService.asmx/GetData",
                    contentType: "application/json; charset=utf-8",
                    data: "{'orderId': " + JSON.stringify(order.OrderId) + "}",
                    dataType: "json",
                    success: function (data) {
                        if (data) {
                            if (data.d.length > 1) {
                                $.each(data, function () {
                                    $.each(this, function (k, v) {
                                        var temp2 = "<input type='button' class='btn' data-bind='value: " + v.TeacherId + ", click: $root.downloadImage' />";
                                        $(".downloadButtons").append(temp2);
                                    });
                                });
                                $("#selectOrderPackagePopup").modal("show");
                            }
                        }
                    },
                    error: function (n) {
                        alert('Error');
                    }
                });

Then I'm able to see the buttons in the modal popup, and this is the generated source:

在此处输入图片说明

The click event is this one:

self.downloadImage = function () {
                if (order) {
                    var url = "DownloadImage.aspx?orderId=" + order.id;
                    window.location = url;
                } 
            };

I'm not able to fire the click event.

You need to call ko.applyBindings after you have added the buttons to the DOM. Place it in your ajax success callback, eg below the $("#selectOrderPackagePopup").modal("show"); line.

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