面向對象編程(成績輸入)

1.js
<body>
    <ul>
        <li id="1">張三:</li>
        <li id="2">李四:</li>
        <li id="3">王五:</li>
    </ul>
    <script>
        window.onload = function(){
            var lis = document.getElementsByTagName('li');
            for(var i=0;i<lis.length;i++){
                new PlaceFieldEditor(lis[i],lis[i].id,'請輸入成績...').addElement();

            }
        }   
    </script>
</body>
2.面向對象
function PlaceFieldEditor(obj,id,tex){
    this.el = obj;
    this.id = id;
    this.value = tex;
    this.inputValue = '';
    //this.addElement();
}
PlaceFieldEditor.prototype.addElement = function(){
    var span = document.createElement('span');
    span.innerHTML = this.value;
    this.node = span;
    this.el.appendChild(this.node);
    var that = this;
    this.el.addEventListener('click',function(e){
        if(e.target.tagName == 'SPAN'){
            that.change();
        }else if(e.target.tagName == 'BUTTON'){
            if(e.target.innerHTML == '取消'){
                that.cancel();
            }else{
                that.inputValue = that.node.children[0].value;
                if(that.inputValue == ""){
                    alert('不能爲空!');
                }else{
                    var reg = /\d+/;
                    if(reg.test(that.inputValue)){
                        that.confirm();
                    }else{
                        alert('只能輸入數字');
                    }
                }
            };
        }
    });
}
PlaceFieldEditor.prototype.change = function(){
        var input = document.createElement('input');
        var button = document.createElement('button');
                button.innerHTML = '保存'
        var button1 = document.createElement('button');
                button1.innerHTML = '取消';
                this.node.innerHTML = "";
                this.node.appendChild(input);
                this.node.appendChild(button);
                this.node.appendChild(button1);
}
PlaceFieldEditor.prototype.cancel = function(){
    this.node.innerHTML = "";
    this.node.innerHTML = this.value;
}
PlaceFieldEditor.prototype.confirm = function(){
    this.value = this.inputValue;
    this.node.innerHTML = this.value;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章