如何在data-bind中设置图像点击属性

时间:2012-04-30 05:03:15

标签: knockout.js

查看:

<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值将是一个奖励。任何一种解决方案都将受到高度赞赏。

3 个答案:

答案 0 :(得分:5)

您不需要使用attr绑定将函数绑定到单击,为此您应该使用Knockout click绑定:

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

答案 1 :(得分:2)

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

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

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

这很好用。

答案 2 :(得分:0)

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