在javascript中从html调用对象方法

Call an object method from html in javascript

本文关键字:对象 方法 调用 html javascript 中从      更新时间:2023-09-26

我为简单的预订系统写了一个类。数据保存在一个数组中,所有的编辑和删除操作都是使用该类中的函数对此数组执行的。如此放置按钮以执行编辑和删除。如何将类中的方法调用到按钮的onclick事件。请检查以下代码。

类文件

/**
 * Class for handling general insert, update, delete 
 * oprations for a room booking system.
 */
var bookingSystem = function (){
    this.editMode = false; 
    this.editIndex = false;
    // option data for Number of  persons drop down
    this.numPersonsOpts = [
        {name : 1, val : 1},
        {name : 2, val : 2},
        {name : 3, val : 3},
        {name : 4, val : 4}
    ];
    // Sample data to show initially
    this.bookingData = [
        {name : "John", roomType : "AC", numPersons : 3},
        {name : "Mishal", roomType : "Non AC", numPersons : 1}
    ];
    var self = this; // get a reference to this. 
    /**
     * Prepare and show options for dropdown
     * @param string selectorId id of the dropdown
     * @param object optionData array object contains name and value for the options 
     */
    this.showOptions = function (selectorId, optionData){
        var optsStr = "";
        for (var i=0; i<optionData.length; i++) {
            optsStr += '<option value='+optionData[i].val+'>'+optionData[i].name+'</option>';
        };
        document.getElementById(selectorId).innerHTML = optsStr;
    }
    /**
     * To save and update data
     */
    this.saveBooking = function (){
        var name = document.getElementById("bookingName").value;
        if(name){
            var singleEntry = {
                name : name,
                roomType : document.querySelector('input[name="roomType"]:checked').value == 1? 'AC' : 'Non AC',
                numPersons : document.getElementById("numPersonSelect").value
            }
            if(self.editMode){
                if(typeof(self.editIndex) == 'number'){
                    self.bookingData[self.editIndex] = singleEntry;
                    self.editIndex = false;
                }
                self.editMode = false;
            }else{
                self.bookingData.push(singleEntry);
            }
            document.getElementById("bookingName").value = '';
            self.renderTemplate();
        }   
    }
    /**
     * To edit a particular item
     * @param number index array index to edit
     */
    self.edit = function (index){
        self.editIndex = index;
        self.editMode = true;
        document.getElementById("bookingName").value = self.bookingData[self.editIndex].name;
        document.querySelector('input[name="roomType"][value="1"]').checked = self.bookingData[self.editIndex].roomType == 'AC'? true: false;
        document.querySelector('input[name="roomType"][value="2"]').checked = self.bookingData[self.editIndex].roomType == 'Non AC'? true: false;
        for(var i=0; i<this.numPersonsOpts.length; i++){
            document.getElementById("numPersonSelect").options[i].selected = false;
        }
        document.getElementById("numPersonSelect").options[(self.bookingData[self.editIndex].numPersons)-1].selected = true;
    }
    /**
     * To delete a particular item
     * @param number index array index to delete
     */
    self.deleteItem = function (index){
        self.bookingData.splice(index,1);
        self.renderTemplate();
    }
    /**
     * To preapre table content and show it.
     */
    this.renderTemplate = function (){
        var template = '';  
        if(self.bookingData.length > 0){
            for(var i= 0; i< self.bookingData.length; i++){
                template += '<tr>';
                template += '<td>'+self.bookingData[i].name+'</td>';
                template += '<td>'+self.bookingData[i].roomType+'</td>';
                template += '<td>'+self.bookingData[i].numPersons+'</td>';
                template += '<td><button type="button" onclick = "edit('+i+')">Edit</button></td>';
                template += '<td><button type="button" onclick = "deleteItem('+i+')">Delete</button></td>';
                template += '</tr>';
            }
        }else{
            template += '<tr>';
            template += '<td colspan="2"> No Data Found.</td>';
            template += '</tr>';
        }
        document.getElementById("renderTable").innerHTML = template;
    }

}

初始化它的通用代码。

var bs = new bookingSystem(); // Create object for bookingSystem
var init= function(){
    bs.showOptions('numPersonSelect',bs.numPersonsOpts); // Show number of persons option
    // Save Button event
    var btn = document.getElementById("saveBookingBtn");
    if(btn.addEventListener){
        btn.addEventListener('click',bs.saveBooking);
    }else{
        btn.attachEvent('onclick',bs.saveBooking);
    }
    bs.renderTemplate();
}
function edit(index){
    bs.edit(index); 
}
function deleteItem(index){
    bs.deleteItem(index);   
}

从主体onload事件调用init()。以下是html代码。

<body onload="init()">
    <form>
        <div class="formRow">
            <label>Name : </label>
            <input type="text" id="bookingName" name="bookingName" value=""> 
        </div>
        <div class="formRow">
            <label>AC/NO : </label>
            <input type="radio" value="1" name="roomType" checked="checked"> AC 
            <input type="radio" value="2" name="roomType"> Non AC 
        </div>
        <div class="formRow">
            <label>Number of Persons</label>
            <select name="numPerson" id="numPersonSelect">
            </select>
        </div>
        <div>
            <button type="button" id="saveBookingBtn">Save</button>
        </div>
    </form>
 <div id="renderArea"></div>
 <table>
    <td>Name</td>
    <td>Room Type</td>
    <td>Person(s)</td>
    <td>Edit</td>
    <td>Delete</td>
    <tbody id="renderTable"></tbody>
 </table>
</body>

此代码运行良好。但在这里,我创建了editdeleteItem方法来调用类中编写的实际编辑和删除方法。如何使用从类直接到onclick事件的方法。像这个<button onclick="bs.edit()">Edit</button>

$(function(){
             var productManagement = function() {
                 var products = [
                                    {id:1, name: 'samsung galaxy', price: 6000, description: 'samsung galaxy mobile phone'},
                                    {id:2, name: 'apple', price: 10000, description: 'apple mobile phone'},
                                    {id:3, name: 'nokia', price: 5000, description: 'nokia mobile phone'},
                                    {id:4, name: 'motorola', price: 7000, description: 'motorola mobile phone'}
                                ];
                  var selectedProducts = {};
                  var $this = this;
                  this.displayProducts = function() {                     
                      $.each(products, function(k, product){                         
                         $('.content').append($this.getProductInfo(product));
                      });
                  }
                  
                  this.getProductInfo = function(product) {
                        var html  = '<div class="item" id="' + product.id + '">';
                            html += '<table><tr><td>Name</td><td>:&nbsp;' + product.name + '</td></tr>';
                            html += '<tr><td>Price</td><td>:&nbsp;' + product.price + '</td></tr>';
                            html += '<tr><td>Description</td><td>:&nbsp;' + product.description + '</td></tr>';
                            html += '<tr><td colspan="2"><button class="addToCart">Add To Cart</td></tr></table>'
                            html += '</div>';
                        return html;
                  }
                  
                  this.delegate = function() {
                      $('body').delegate('.addToCart', 'click', function(){
                          var id = $(this).closest('div').attr('id');
                          if( selectedProducts[id] == undefined) {
                              selectedProducts[id] = 1;
                          }else{
                              selectedProducts[id]++;
                          }
//                          selectedProducts.push(id);
                          $('.content').hide();
                          $('.cart').show();
                          $this.showCart();
                      });
                      $('body').delegate('#continueShopping', 'click', function(){
                          $('.content').show();
                          $('.cart').hide();
                      });
                      
                      $('body').delegate('.remove', 'click', function(){                          
                          var id = $(this).closest('tr').attr('id');                          
                          $this.removeFromSelected(id);
                      });
                  }
                  
                  this.removeFromSelected = function(productId){
                      $.each(selectedProducts, function(pid, numberOfItems){
                          if( pid == productId) {
                              delete selectedProducts[pid];                              
                              return false;
                          }
                      });
                      $this.showCart();
                  }
                  
                  this.showCart = function() {
                      var html = '<table><tr><th>Name</th><th>Unit Price</th><th>No of Items</th><th>Total Price</th><th>Action</th></tr>';
                      var total = 0;                      
                      $.each(selectedProducts, function(productId,numberOfItems){                         
                         var productInfo = $this.getProduct(productId);                             
                             html += '<tr id="' + productId + '"><td>' + productInfo.name + '</td><td>' + (productInfo.price) + '</td><td>'+ numberOfItems + '</td><td>' + (productInfo.price * numberOfItems) + '</td><td><button class="remove">Remove</button></td></tr>';                                
                             total += productInfo.price;
                      });
                      html += '</table>';
                      html += '<br /><br />Grand Total:' + total;
                      $('#cartItems').empty();
                      $('#cartItems').append(html);
                  }
                  
                  this.getProduct = function(productId) {
                      var found = {};
                      $.each( products, function(id, product){                          
                          if( product.id == productId) {                              
                              found = product;
                              return false;
                          }
                      })
                      return found;
                  }
             }
             
             var PM  = new productManagement();
             PM.delegate();
             PM.displayProducts();
         }) 
 .header {
                background-color:#E0E8FF;
                padding:5px;
                text-align:center;
            }
            .content {
                padding-left:15%;
                padding-top:40px;
                width:100%;
                overflow:auto
            }
            .cart {
                padding-left:15%;
                padding-top:40px;
                width:100%;                
            }
            .footer {
                background-color:#E0E8FF;
                text-align:center;
            }
            .item {
                width:25%;
                height:150px;
                overflow:auto;
                border:1px solid black;
                float:left
            }

加载文档时,要删除的上下文中不存在您正在调用的函数。通过将函数定义为全局函数,它正在工作。

/**
     * Class for handling general insert, update, delete 
     * oprations for a room booking system.
     */
    var bookingSystem = function (){
        this.editMode = false; 
        this.editIndex = false;
        // option data for Number of  persons drop down
        this.numPersonsOpts = [
            {name : 1, val : 1},
            {name : 2, val : 2},
            {name : 3, val : 3},
            {name : 4, val : 4}
        ];
        // Sample data to show initially
        this.bookingData = [
            {name : "John", roomType : "AC", numPersons : 3},
            {name : "Mishal", roomType : "Non AC", numPersons : 1}
        ];
        var self = this; // get a reference to this. 
        /**
         * Prepare and show options for dropdown
         * @param string selectorId id of the dropdown
         * @param object optionData array object contains name and value for the options 
         */
        this.showOptions = function (selectorId, optionData){
            var optsStr = "";
            for (var i=0; i<optionData.length; i++) {
                optsStr += '<option value='+optionData[i].val+'>'+optionData[i].name+'</option>';
            };
            document.getElementById(selectorId).innerHTML = optsStr;
        }
        /**
         * To save and update data
         */
        this.saveBooking = function (){
            var name = document.getElementById("bookingName").value;
            if(name){
                var singleEntry = {
                    name : name,
                    roomType : document.querySelector('input[name="roomType"]:checked').value == 1? 'AC' : 'Non AC',
                    numPersons : document.getElementById("numPersonSelect").value
                }
                if(self.editMode){
                    if(typeof(self.editIndex) == 'number'){
                        self.bookingData[self.editIndex] = singleEntry;
                        self.editIndex = false;
                    }
                    self.editMode = false;
                }else{
                    self.bookingData.push(singleEntry);
                }
                document.getElementById("bookingName").value = '';
                self.renderTemplate();
            }   
        }
        /**
         * To edit a particular item
         * @param number index array index to edit
         */
        self.edit = function (index){
            self.editIndex = index;
            self.editMode = true;
            document.getElementById("bookingName").value = self.bookingData[self.editIndex].name;
            document.querySelector('input[name="roomType"][value="1"]').checked = self.bookingData[self.editIndex].roomType == 'AC'? true: false;
            document.querySelector('input[name="roomType"][value="2"]').checked = self.bookingData[self.editIndex].roomType == 'Non AC'? true: false;
            for(var i=0; i<this.numPersonsOpts.length; i++){
                document.getElementById("numPersonSelect").options[i].selected = false;
            }
            document.getElementById("numPersonSelect").options[(self.bookingData[self.editIndex].numPersons)-1].selected = true;
        }
        /**
         * To delete a particular item
         * @param number index array index to delete
         */
        self.deleteItem = function (index){
            console.log("called once");
            self.bookingData.splice(index,1);
            self.renderTemplate();
        }
        /**
         * To preapre table content and show it.
         */
        this.renderTemplate = function (){
            var template = '';  
            if(self.bookingData.length > 0){
                for(var i= 0; i< self.bookingData.length; i++){
                    template += '<tr>';
                    template += '<td>'+self.bookingData[i].name+'</td>';
                    template += '<td>'+self.bookingData[i].roomType+'</td>';
                    template += '<td>'+self.bookingData[i].numPersons+'</td>';
                    template += '<td><button type="button" onclick = "return callEdit('+i+')">Edit</button></td>';
                    template += '<td><button type="button" onclick = "return callDelete('+i+')">Delete</button></td>';
                    template += '</tr>';
                }
            }else{
                template += '<tr>';
                template += '<td colspan="2"> No Data Found.</td>';
                template += '</tr>';
            }
            document.getElementById("renderTable").innerHTML = template;
        }

        this.init= function(){
            console.log("called");
            self.showOptions('numPersonSelect',self.numPersonsOpts); // Show number of persons option
            // Save Button event
            var btn = document.getElementById("saveBookingBtn");
            if(btn.addEventListener){
                btn.addEventListener('click',self.saveBooking);
            }else{
                btn.attachEvent('onclick',self.saveBooking);
            }
            self.renderTemplate();
        }

    }

    var bs = new bookingSystem(); // Create object for bookingSystem
        bs.init();
    window.callEdit = function(index){
        bs.edit(index);
    }
    window.callDelete = function(index){
        bs.deleteItem(index);
    }

请在此处查看此示例