jquery - 将图像 src 绑定(bind)为 Knockout 中的表达式

标签 jquery .net asp.net-mvc knockout.js

如果您觉得这个问题很愚蠢,请耐心等待。我是 knockout 的初学者,正在努力学习它。

我想将图像源绑定(bind)到表达式。该表达式负责生成路径,并且该路径必须作为 img 的源应用。

<ul id='AllPatient' data-role='listview' data-inset='true' data-bind="foreach:Patients">
            @*<li><span data-bind="text: ko.toJSON($data)"></span></li>*@
            <li>
                <table class="Tabular">
                    <tr>
                        <td class="DataCell">
                            <a href="javascript:" id="pLocation" sortorder="none"><span data-bind="text:$data.UnitName">
                            </span></a>
                        </td>
                        <td class="DataCellImage">
                            <a href="javascript:" id="addPatient" sortorder="none" data-bind="click:$root.addPatient">
                                <img data-bind="attr:{src: $root.ImageSource}" src="~/Content/Images/MPL/PersonAdd.png" /></a>
                        </td>
                    </tr>
                </table>
            </li>
        </ul>

我正在使用以下数据绑定(bind) ViewModel:

function PatientsModel(data)
{
    var self = this;

    self.Patients = ko.observableArray([]);

    self.Patients(data.Patients);
    self.ImageSource = function (model)
    {
        if (model.myPatient == true)
        {
            return PyxisLinkJS.RootURL + '/Content/Images/MPL/MyPatientGray.png';
        }
        else if (model.localPatient == true)
        {
            return PyxisLinkJS.RootURL + '/Content/Images/MPL/PersonAdd.png';
        }
        else
        {
            return PyxisLinkJS.RootURL + '/Content/Images/MPL/MyPatientGray.png';
        }
    }
}

这就是发生的事情:它试图将 ImageSource 的函数体设置为 Image 的 src。我想触发ImageSource方法并将返回值设置为Image的Src。

问候, 苏米特

最佳答案

它返回函数而不是字符串,将其称为函数

<img data-bind="attr:{src: $root.ImageSource() }" src="~/Content/Images/MPL/PersonAdd.png" />

此外,您可以将这两者结合起来:

self.Patients = ko.observableArray([]);
self.Patients(data.Patients);

// Into this
self.Patients = ko.observableArray( data.Patients );

关于jquery - 将图像 src 绑定(bind)为 Knockout 中的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13154329/

相关文章:

asp.net-mvc - 在 asp net mvc 和 jquery 中使用富文本编辑器发布的问题

jquery - 如何通过单击按钮使用 removeClass 和 addClass

jquery - 不支持的浏览器上的 html5 必需属性

C# 动态加载程序集

c# - 框架类库(FCL) 是分别为C# 和C++ 实现的吗?

c# - 将文件拖放到 WPF 中

asp.net-mvc - 文件输入MVC 3所需的客户端验证

javascript - 参数字典包含不可为 null 类型 'talepID' 的参数 'System.Int32' 的 null 条目

jquery - 如果函数到达其 "if"语句,如何防止函数执行某些操作?

javascript - 动态创建的元素不可拖动