天天看点

面向对象编程(成绩输入)

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

复制

面向对象编程(成绩输入)
面向对象编程(成绩输入)