knockout事件绑定

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
		<script type="text/javascript" src="js/knockout-3.5.0beta.debug.js" ></script>
		<script type="text/javascript">
            //创建一个View对象
            function ViewModel() {
                var self = this;
                //使用observableArray进行绑定可以动态变更option选项
                self.selectOptions = ko.observableArray([{
                    "text": "请选择",
                    "value": "0"
                }]);
                self.result = ko.observable("0"); //添加result监控属性,初始绑定值为0
                addfunction=function(){
                	alert(123);
                };
            }
            

            $(function() {
                var vm = new ViewModel();
                ko.applyBindings(vm);
                $("#btnAddItem").click(function() {
                    vm.selectOptions.push({
                        "text": $("#txtOptText").val(),
                        "value": $("#txtOptValue").val()
                    });
                });
            });
        </script>
	</head>
	<body>
		 <div style=" background-color:#0094ff; width:180px; margin:100px auto auto auto;">
            <select style="background-color:ActiveCaption;width:100px" data-bind="options: selectOptions, optionsText: 'text', optionsValue: 'value', value: result">
            </select>
            Value=
            <span data-bind="    text: result">
            </span>
            <div>
                Text:
                <input id="txtOptText" value="选项1" />
            </div>
            <div>
                Value:
                <input id="txtOptValue" value="1" />
            </div>
            <input type="button" data-bind="click: addfunction" value="新增选项" id='btnAddItem' />
        </div>
	</body>
</html>

  

posted on 2018-03-08 08:26  行周  阅读(712)  评论(0编辑  收藏  举报

导航