【问题标题】:How to set image's click attribute in data-bind如何在数据绑定中设置图像的点击属性
【发布时间】:2017-08-21 17:12:04
【问题描述】:

查看:

<td style="white-space: nowrap;">
   <img data-bind="attr: { onclick: PlaySounds }" src="/Images/audioGreen.png" alt="Pronounce word" title="Pronounce word" style="cursor: pointer" />
   <a data-bind="attr: { href: GoogleQuery }" target="_blank">
      <img src="/Images/googleIcon.png" alt="Google Search" title="Google Search" style="cursor: pointer" />
   </a>
</td>

淘汰视图模型:

function DictionaryEntry() {
   var self = this;
   self.Simplified = ko.observable("");
   self.Traditional = ko.observable("");
   self.Phonetic = ko.observable("");
   self.Definition = ko.observable("");

   self.GoogleQuery = ko.computed(function () {
       return "http://www.google.com/search?q=" + self.Simplified();
   }, self);

   self.PlaySounds = ko.computed(function () {
       return "playSounds('" + self.Phonetic() + "')";
   }, self);
}

关于“attr”绑定的信息:“http://knockoutjs.com/documentation/attr-binding.html

错误详情:

Microsoft JScript 运行时错误:无法解析绑定。 消息:ReferenceError:“PlaySounds”未定义; 绑定值:attr: { onclick: PlaySounds }

不知道我哪里出错了。如果可能,直接绑定而不使用 ko.computed 值将是一个好处。无论哪种方式的解决方案都将不胜感激。

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    您不需要使用 attr 绑定来将功能绑定到点击,为此您应该使用 Knockout click 绑定:

    <img data-bind="click: playSounds" src="/Images/audioGreen.png"
         alt="Pronounce word" title="Pronounce word" style="cursor: pointer" />
    

    【讨论】:

    • 嗨 Colin,我知道点击绑定,但据我所知,它不允许我传入淘汰变量,是吗?例如,从我的 viewModel 中传入“Phonetic”的语法是什么?
    • 顺便说一句,我刚刚评论了一行,可以看到我在为 Google Query 链接出价时遇到了同样的错误
    【解决方案2】:

    我正在回答我自己的问题...有点晚了,但我希望它对其他人有所帮助:

    我所做的是使用:click: $root.PlaySounds 并在我的主 ViewModel 中使用该功能..而不是 DictionaryEntry(子)模型..像这样:

    self.PlaySounds = function (entry) {
                    playSounds(entry.Phonetic);
                    return false;
                };
    

    效果很好。

    【讨论】:

      【解决方案3】:

      你想要的绑定是click: function() { playSounds(Phonetic()) }。如果您希望我们实际调试特定错误,请提供您的代码示例(例如在 jsfiddle 中)。

      【讨论】:

      • 谢谢迈克尔,但这也不起作用。我将其更改为:“
      • 听起来好像无法访问 playSounds 功能。该函数是如何定义的?它要么需要成为您的视图模型的一部分,要么需要全局定义。
      • 也可能是无法访问Phonetic。这意味着您的视图模型不可访问。不幸的是,没有看到你的更多代码,我无法为你调试。
      猜你喜欢
      • 2012-02-19
      • 2020-01-09
      • 2020-01-04
      • 2021-03-23
      • 1970-01-01
      • 2021-01-10
      • 2012-06-22
      • 2014-12-26
      • 2020-08-08
      相关资源
      最近更新 更多