【问题标题】:Binding Image src as Expression in Knockout将图像 src 绑定为 Knockout 中的表达式
【发布时间】:2012-10-20 16:44:46
【问题描述】:

如果你觉得这个问题很愚蠢,请多多包涵。我是淘汰赛的初学者,正在努力学习。

我想将图像源绑定到表达式。表达式负责生成路径,并且该路径必须作为源应用到 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>

我正在使用以下数据绑定 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。

问候, 苏梅特

【问题讨论】:

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


    【解决方案1】:

    它返回的是函数而不是字符串,称之为函数

    <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 );
    

    【讨论】:

    • 未捕获的错误:无法解析绑定。消息:TypeError:无法设置未定义的属性“myPatient”;绑定值:attr:{src: $root.ImageSource()}
    • 谢谢牧师,请忽略我之前的评论。我现在可以找到该方法被调用,但我认为问题是将模型传递给 ImageSource() 方法。可以提示我吗?这样我就可以使用当前模型,来决定返回图像源。
    • 我通过 $data 让它现在工作,我希望方法是合适的:
    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 2012-07-03
    • 2018-12-08
    • 2019-05-25
    相关资源
    最近更新 更多