javascript - 避免Javascript(JQuery)中的冗余代码

标签 javascript jquery ajax

我为我的项目编写了一个脚本,允许用户使用 JS、PHP 和 MySql 管理库存。用户可以通过点击按钮来选择库存位置并更新产品的数量。这个过程使用AJAX调用来实时更新前端和后端。

我的代码可以工作,但是,由于代码冗余量,我对执行不满意。我有两个添加和删除 AJAX 功能,以便更新网站上显示的第一个库存位置。但为了允许用户在选择新位置后继续执行此操作,我必须重用嵌套在选择位置 Ajax 代码中的这两个函数的代码。我的 JS 技能不是那么强,我想知道 JQuery 是否可以提供更好的代码内聚性。在 PHP 中,我会创建一个类和函数来执行此任务,以避免代码重用。我可以在 JQuery 中实现类似的功能吗?

// This script is used update and display changes to inventory displayed on cp.php
$(document).ready(function() {
    var this_item;
    var itemid;
    var count;
    
    // Store the first table from the MySQL Database and display it to the page
    var location = $('.location_select').attr('title');
    $('.default_location').empty();
    $('.default_location').append(location);
    
    
    // Add to the inventory count of the selected product
    $('.glyphicon-plus').click(function() {
        event.preventDefault();
        // Store the selected product name and update its display count on the page
        this_item = $(this).attr('title');
        itemid = this_item.substr(0, this_item.length - 1);
        count = parseInt($('#'+itemid).text());
        count++;
        
        // Send the inventory count to modifyproduct.php and update new count to MySQL
        $.ajax ({
            url: 'modifyproduct.php',
            type: 'GET',
            data: {
                location: location,
                itemid: itemid,
                count: count,
            },
                
            success: function(serverResponse) {
                    $('#'+itemid).hide();
                    $('#'+itemid).html(count).delay(170);
                    $('#'+itemid).fadeIn();
            }
                
        });
    });
    
    // Remove from the select inventory count
    $('.glyphicon-minus').click(function() {
        event.preventDefault();
        // Store the selected product name and update its display count on the page
        this_item = $(this).attr('title');
        itemid = this_item.substr(0, this_item.length - 1);
        count = parseInt($('#'+itemid).text());
        count--;
        
        // Send the inventory count to modifyproduct.php and update new count to MySQL
        $.ajax ({
            url: 'modifyproduct.php',
            type: 'GET',
            data: {
                location: location,
                itemid: itemid,
                count: count,
            },
                
            success: function(serverResponse) {
                    $('#'+itemid).hide();
                    $('#'+itemid).html(count).delay(170);
                    $('#'+itemid).fadeIn();
            }
                
        });
    });
    
    // Select inventory location to be displayed from .location_select menu
    $('.location_select').click(function(){
        location = $(this).attr('title');
        $('.default_location').empty();
        $('.default_location').append(location);
        $.ajax ({
            url: 'display.php',
            type: 'GET',
            data: {
                location: location,
            },
            
            success: function(serverResponse) {
                $('#display_inventory').fadeOut('slow');
                $('#display_inventory').empty();
                $('#display_inventory').hide();
                $('#display_inventory').append(serverResponse);
                $('#display_inventory').fadeIn('slow');
    
                $('.glyphicon-plus').click(function() {
                    event.preventDefault();
                    this_item = $(this).attr('title');
                    itemid = this_item.substr(0, this_item.length - 1);
                    count = parseInt($('#'+itemid).text());
                    count++;
                    
                    $.ajax ({
                        url: 'modifyproduct.php',
                        type: 'GET',
                        data: {
                            location: location,
                            itemid: itemid,
                            count: count,
                        },
                            
                        success: function(serverResponse) {
                                $('#'+itemid).hide();
                                $('#'+itemid).html(count).delay(170);
                                $('#'+itemid).fadeIn();
                        }
                            
                    });
                });
                
                $('.glyphicon-minus').click(function() {
                    event.preventDefault();
                    this_item = $(this).attr('title');
                    itemid = this_item.substr(0, this_item.length - 1);
                    count = parseInt($('#'+itemid).text());
                    count--;
                    
                    $.ajax ({
                        url: 'modifyproduct.php',
                        type: 'GET',
                        data: {
                            location: location,
                            itemid: itemid,
                            count: count,
                        },
                            
                        success: function(serverResponse) {
                                $('#'+itemid).hide();
                                $('#'+itemid).html(count).delay(170);
                                $('#'+itemid).fadeIn();
                        }
                            
                    });
                });
                
            }
        })
    });
});

最佳答案

功能为first class citizens因此在 JS 中

var fn = function() { ... }

在您的代码中,我发现唯一改变的是 count 的值

我会执行以下操作

var modifyItem = function(quantity) {
  return function() {
    event.preventDefault();
    this_item = $(this).attr('title');
    itemid = this_item.substr(0, this_item.length - 1);
    count = parseInt($('#' + itemid).text());
    // note that quantity is added here
    count += quantity
    $.ajax({
      url: 'modifyproduct.php',
      type: 'GET',
      data: {
        location: location,
        itemid: itemid,
        count: count,
      },
      success: function(serverResponse) {
        $('#' + itemid).hide();
        $('#' + itemid).html(count).delay(170);
        $('#' + itemid).fadeIn();
      }
    });
  }
}

然后使用返回值(函数)作为要完成的操作

$('.glyphicon-plus').click(modifyItem(+1))
$('.glyphicon-minus').click(modifyItem(-1))

关于javascript - 避免Javascript(JQuery)中的冗余代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829232/

相关文章:

javascript - 获取以前的数据属性

jquery - 错误: Permission denied to access property 'document' in iFrame

ajax - 在 Cakephp 2.0 中测试 Ajax 请求

ajax - aria-controls 究竟为用户做什么?它如何受 AJAX 使用的影响?

javascript - 带有单独背景幻灯片的 slider

javascript - 单击时从 AJAX .each() 循环追加数据

javascript - 无需点击即可启动 Angular 函数?

javascript - 如何在最大宽度 768px 上禁用 jquery 功能?

javascript - 使用 $resource 和 $q 初始化 $scope 变量

jQuery dataTables - 从单元格中删除 HTML 元素