【问题标题】:Knockout Click event not working淘汰赛点击事件不起作用
【发布时间】:2017-09-11 12:14:50
【问题描述】:

我正在为自己(可能还有未来的其他人)制作天气页面,但在显示和隐藏天气警报的按钮上遇到了问题。你可以view the page 看看我在做什么。 (抱歉,我选择了 FL,但他们现在有很多警报)。

Page Source

JS Source

我的警报进入一个数组,对于每个项目,我需要一个按钮来显示和隐藏警报。我的页面源包含:

<div data-bind="foreach: alertsViewModel.features">
    <div class="col-12">
        <div class="alert alert-danger" role="alert">
            <p>
                <strong data-bind="text: properties.headline"></strong>
                <button type="button" class="btn btn-link" data-bind="click: $root.showHideAlert">Show</button>
            </p>
            <div data-bind="attr: {id: properties.id}" style="display: none;">
                <p data-bind="lineBreaks: properties.description"></p>
                <p><strong>Instructions</strong></p>
                <p data-bind="lineBreaks: properties.instruction"></p>
            </div>
        </div>
    </div>
</div>

我的 ViewModel 看起来像:

// ==================
// Alerts View Model
// ==================
var alertsViewModel = {

    features: ko.observableArray([]),
    hwoUrl: ko.observable(""),
    hwoText: ko.observable(""),
    showHideAlert: function(data, event){
        alert('you clicked');
        /*$('#hwo').toggle('slow',function(){
            if ($('#showHwo').text() == "Show")
            {
                $('#showHwo').text("Hide");
            } 
            else 
            {
                $('#showHwo').text("Show");
            }
        });*/
    }
};

ko.applyBindings(weatherViewModel, document.getElementById('weather-alerts'));

我尝试了几种不同的方法,但都无法正常工作。 (因此注释代码和警报)。这很奇怪,因为我过去做过几次,没有任何问题。我确定这是我错过的简单事情。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    可能是因为您在调用 ko.applyBindings 时使用了 weatherViewModel 而不是 alertsViewModel?

    我认为按钮绑定中的 $root 指的是 weatherViewModel,因为那是 ko 应用的 VM。

    也许可以尝试更改函数的位置,或者直接使用 alertViewModel。

    【讨论】:

    • 我责怪 1 am 编程...感谢您的帮助,我完全错过了。我现在觉得自己好傻。
    • 没有问题 :) 凌晨 1 点编程 ftw
    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多