knockout.js - modify DOM in current item in list (expand list item subsection) using templates

倾然丶 夕夏残阳落幕 提交于 2019-12-12 03:14:46

问题


In this example I want to use knockout.js to allow the "Expand" link to be clicked and have its text changed to "Collapse". I also want to set the make the jobDetails section visible. This is a very general question of how to get knockout.js to specifically modify the DOM of the "current" item in a list using a click handler.

<script type="text/html" id="job-template">
    <div class="jobContainer">
        <label data-bind="text: JobTitle"></label> 
        <label data-bind="text: CompanyName"></label>
        <div class="jobDetails">
            <label data-bind="text: City"></label>
            <label data-bind="text: State"></label>
        </di>
    <div>
        <a class="expand" href="#" data-bind="click: ???">Expand</a>        
    </div>
    </div>    
</script>

回答1:


This is very straight forward with KO. Here's a simple way to do it. FYI I had to fix your markup slightly.

<div>
    <div class="jobContainer">
        <label data-bind="text: JobTitle"></label>
        <label data-bind="text: CompanyName"></label>
        <div class="jobDetails" data-bind="visible: expanded">
            <label data-bind="text: City"></label>
            <label data-bind="text: State"></label>
        </div>
    <div>
    <a class="expand" href="#" data-bind="click: toggle, text: linkLabel">Expand</a>        
</div>   


var viewModel = function() {
    this.JobTitle = ko.observable("some job");
    this.CompanyName = ko.observable("some company");
    this.City = ko.observable("some city");
    this.State = ko.observable("some state");

    this.someValue = ko.observable().extend({ defaultIfNull: "some default" });

    this.expanded = ko.observable(false);

    this.linkLabel = ko.computed(function () {
        return this.expanded() ? "collapse" : "expand";
    }, this);      

    this.toggle = function () {
        this.expanded(!this.expanded());
    };
};

http://jsfiddle.net/madcapnmckay/XAzW6/

Hope this helps.



来源:https://stackoverflow.com/questions/10577326/knockout-js-modify-dom-in-current-item-in-list-expand-list-item-subsection-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!