【问题标题】:how to create dynamic arrays in javascript on button click如何在单击按钮时在 javascript 中创建动态数组
【发布时间】:2020-07-30 02:58:29
【问题描述】:

我正在构建一个示例 javascript 程序,其中我动态创建了按钮和 div 标签,并且我正在从本地 JSON 文件中获取数据,我想添加一个新功能 即 单击按钮时,应创建一个与按钮名称相同的数组,以便我可以推送与按钮名称匹配的数据。

// -------- TESTING CODE--------

// var clicks=0;
var data = {
    "Sheet1": [
        {
            "PlanName": "Mom's Love",
            "Price": "80",
            "DeliveryType": "Weekly",
            "BillingType": "Monthly",
            "Savings": "80",
            "NoOfDeliveries": "55",
            "FinalPrice": "4320"
        },
        {
            "PlanName": "Mom's Love",
            "Price": "80",
            "DeliveryType": "Monthly",
            "BillingType": "Monthly",
            "Savings": "90",
            "NoOfDeliveries": "14",
            "FinalPrice": "1030"
        },
        {
            "PlanName": "Mom's Love",
            "Price": "80",
            "DeliveryType": "Bi-Weekly",
            "BillingType": "Monthly",
            "Savings": "100",
            "NoOfDeliveries": "27",
            "FinalPrice": "2060"
        },
        {
            "PlanName": "Mom's Love",
            "Price": "80",
            "DeliveryType": "Custom",
            "BillingType": "Monthly",
            "Savings": "110",
            "NoOfDeliveries": "7",
            "FinalPrice": "450"
        },
        {
            "PlanName": "Bloom Box",
            "Price": "75",
            "DeliveryType": "Weekly",
            "BillingType": "Monthly",
            "Savings": "120",
            "NoOfDeliveries": "55",
            "FinalPrice": "4005"
        },
        {
            "PlanName": "Bloom Box",
            "Price": "75",
            "DeliveryType": "Monthly",
            "BillingType": "Monthly",
            "Savings": "130",
            "NoOfDeliveries": "55",
            "FinalPrice": "3995"
        },
        {
            "PlanName": "Bloom Box",
            "Price": "75",
            "DeliveryType": "Bi-Weekly",
            "BillingType": "Monthly",
            "Savings": "140",
            "NoOfDeliveries": "55",
            "FinalPrice": "3985"
        },
        {
            "PlanName": "Bloom Box",
            "Price": "75",
            "DeliveryType": "Custom",
            "BillingType": "Monthly",
            "Savings": "150",
            "NoOfDeliveries": "55",
            "FinalPrice": "3975"
        },
        {
            "PlanName": "Paradise",
            "Price": "96",
            "DeliveryType": "Weekly",
            "BillingType": "Monthly",
            "Savings": "160",
            "NoOfDeliveries": "55",
            "FinalPrice": "5120"
        },
        {
            "PlanName": "Paradise",
            "Price": "96",
            "DeliveryType": "Monthly",
            "BillingType": "Monthly",
            "Savings": "170",
            "NoOfDeliveries": "55",
            "FinalPrice": "5110"
        },
        {
            "PlanName": "Paradise",
            "Price": "96",
            "DeliveryType": "Bi-Weekly",
            "BillingType": "Monthly",
            "Savings": "180",
            "NoOfDeliveries": "55",
            "FinalPrice": "5100"
        },
        {
            "PlanName": "Paradise",
            "Price": "96",
            "DeliveryType": "Custom",
            "BillingType": "Monthly",
            "Savings": "190",
            "NoOfDeliveries": "55",
            "FinalPrice": "5090"
        },
        {
            "PlanName": "Romance ",
            "Price": "105",
            "DeliveryType": "Weekly",
            "BillingType": "Monthly",
            "Savings": "200",
            "NoOfDeliveries": "55",
            "FinalPrice": "5575"
        },
        {
            "PlanName": "Romance ",
            "Price": "105",
            "DeliveryType": "Monthly",
            "BillingType": "Monthly",
            "Savings": "210",
            "NoOfDeliveries": "55",
            "FinalPrice": "5565"
        },
        {
            "PlanName": "Romance ",
            "Price": "105",
            "DeliveryType": "Bi-Weekly",
            "BillingType": "Monthly",
            "Savings": "220",
            "NoOfDeliveries": "55",
            "FinalPrice": "5555"
        },
        {
            "PlanName": "Romance ",
            "Price": "105",
            "DeliveryType": "Custom",
            "BillingType": "Monthly",
            "Savings": "230",
            "NoOfDeliveries": "55",
            "FinalPrice": "5545"
        }


    ]
}

var newArr = [];
var containerDiv, containerDivRows, containerDivCols;
// obj = new Object();
function init() {
    for (var i = 0; i < data.Sheet1.length; i++) {

        newArr.push(data.Sheet1[i].DeliveryType);

    }
    console.log("Array with duplicates below....");
    console.log(newArr);


    /*
    Basically, we iterate over the array and, for each element, check if the first position of this element in the array is equal to the current position. 
    Obviously, these two positions are different for duplicate elements.
    Using the 3rd ("this array") parameter of the filter callback we can avoid a closure of the array variable:
    */

    newArr = newArr.filter(function (item, pos) {
        return newArr.indexOf(item) == pos;
    });
    console.log("Array without duplicates below....");
    console.log(newArr);


    //-------------TESTING CODE FOR CREATING BUTTONS---------------
    for (var j = 0; j < newArr.length; j++) {
        console.log(newArr[j]);
        var btn = document.createElement("button");
        btn.innerHTML = newArr[j];
        btn.className = newArr[j] + " " + "btn btn-light";
        btn.style.marginLeft = "10px";
        document.body.appendChild(btn);
    }



    //----------TESTING CODE FOR CREATING EMPTY SPACE USING "BR" TAG-----------
    var mainBr = document.createElement("br");
    document.body.appendChild(mainBr);



    // ---------TESTING CODE FOR CREATING CONTAINER DIV--------
    containerDiv = document.createElement("div");
    containerDiv.className = "container";
    containerDiv.id="container"
    containerDiv.style.display="inline-block";
    containerDiv.style.marginLeft="10%";
    document.body.appendChild(containerDiv);



    // ---------TESTING CODE FOR CREATING CONTAINER DIV'S ROWS USING BOOTSTRAP--------
    containerDivRows = document.createElement("div");
    containerDivRows.className = "row";
    containerDivRows.id="row";
    document.body.appendChild(containerDiv).appendChild(containerDivRows);

    /*
    // ---------TESTING CODE FOR CREATING CONTAINER'S COL USING BOOTSTRAP--------
    containerDivCols = document.createElement("col");
    containerDivCols.className = "col-md-4";
    document.body.appendChild(containerDiv).appendChild(containerDivRows).appendChild(containerDivCols);
    */
}
init();



function displayData(btnName) {
    console.log("hello....");
    console.log(btnName);


    // ----------TESTING CODE FOR CLEARING THE "ROW" DIV ELEMENTS IF IT CONTAINS ANY ELEMENTS(DIV)-------------- 
    const myNode = document.getElementById("row");
    myNode.innerHTML = '';


    // ----------TESTING CODE FOR CREATING THE DIV ELEMENTS INSIDE ROW DIV-------------- 
    
    for (var k = 0; k < 6; k++) {
        var myDiv = document.createElement("div");
        myDiv.className=`dataDiv-${k}`;
        myDiv.style.marginTop = "30px";
        myDiv.style.marginLeft="30px";
        myDiv.style.width = '300px';
        myDiv.style.height = '200px';
        myDiv.style.border="1px solid black";
        myDiv.style.float = "left";
        myDiv.style.position = "relative";
        myDiv.style.display = "inline";
        document.body.appendChild(containerDiv).appendChild(containerDivRows).appendChild(myDiv);
    }
    


    // --------------TESTING CODE FOR CREATING DIV ACCORDING TO NUMBER OF PLAN NAMES IN JSON DATA--------------


    

    



    // -------------TESTING CODE TO DISPLAY DATA INSIDE DIV--------------

    


}





//-------------------ADDING THE EVENT LISTENER ON "WEEKLY" BUTTON---------------------




document.querySelector(".Weekly").addEventListener("click", () => {

    var button = event.target;
    console.log(`${button.innerHTML} clicked....`);
    // displayData()
    displayData(button.innerHTML);
    

});



//-------------------ADDING THE EVENT LISTENER ON "BI-WEEKLY" BUTTON---------------------



document.querySelector(".Bi-Weekly").addEventListener("click",()=>{

    var button = event.target;
    console.log(`${button.innerHTML} clicked....`);
    // displayData();
    displayData(button.innerHTML);
});



//-------------------ADDING THE EVENT LISTENER ON "MONTHLY" BUTTON---------------------



document.querySelector(".Monthly").addEventListener("click",()=>{

    var button = event.target;
    console.log(`${button.innerHTML} clicked....`);
    // displayData();
    displayData(button.innerHTML);

});




//-------------------ADDING THE EVENT LISTENER ON "CUSTOM" BUTTON---------------------



document.querySelector(".Custom").addEventListener("click",()=>{

    var button = event.target;
    console.log(`${button.innerHTML} clicked....`);
    // displayData();
    displayData(button.innerHTML);

});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ditstek Innovations Pvt Ltd</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="shortcut icon" href="#" />
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>

在这里,我通过从 JSON 数组 中获取属性 "DeliveryType" 作为按钮名称来创建按钮,并希望以相同的名称创建数组。例如:每周、双周、每月、自定义

有什么解决办法吗?

【问题讨论】:

  • 请澄清an array of same name as of button should be created 的意思。您不太可能想要命名一个数组,但这是最明显的解释。
  • newArr = [...new Set(newArr)]newArr = newArr.filter(function(item, pos) {return newArr.indexOf(item) == pos;}); 相同
  • GirkovArpa :“应创建与按钮同名的数组”意味着如果我创建名称为每周、每两周、每月和自定义的动态按钮,那么我想动态创建数组它应该与按钮的名称相同,例如每周、双周、每月、自定义

标签: javascript html bootstrap-4


【解决方案1】:

你可以在这里使用字典。下面是示例代码。

var buttonsData = {};

document.querySelector(".Weekly").addEventListener("click", () => {
    
    var button = event.target;
    // check to verify if any key with the button name already exists
    if (buttonsData[button.innerHTML] === undefined)
    {
       // If undefined initialize to an empty array
         buttonsData[button.innerHTML] = [];
    }
    
    buttonsData[button.innerHTML].push(push your data here to array);

    console.log(`${button.innerHTML} clicked....`);
    // displayData()
    displayData(button.innerHTML);       

});

【讨论】:

  • Sowmyadhar Gourishetty:非常感谢您的帮助...祝您有美好的一天..!!!!!!
【解决方案2】:

我想我明白,如果你点击一个值为“Custom”的按钮,你想要一个名为 Custom 的数组,比如 Custom = [],你可以用一个对象轻松地做到这一点。

var btnNames = {};

// Event Listeners.. 

document.querySelector(".Custom").addEventListener("click",()=>{

    var button = event.target;

    // Add array named Custom to arrayWithBtnNames
    var arrayName = button.innerHTML;
    btnNames[arrayName] = [];

    /* 
    Or since your event listener is already tied to a button with the 
    value of Custom I assume. You can just do
    */
    btnNames["Custom"] = [];

    console.log(`${button.innerHTML} clicked....`);
    // displayData();
    displayData(button.innerHTML);

});

【讨论】:

  • radlaz : 非常感谢您的帮助...祝您有美好的一天..!!!!!!
猜你喜欢
  • 1970-01-01
  • 2011-09-05
  • 2016-12-04
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多