javascript - 如何使用javascript删除数组中的项目?

标签 javascript jquery arrays

这是 html:

<button id="btn1">CLICK 1</button>
<button id="btn2">CLICK 2</button>
<div id="show"></div>

这是 JavaScript:

product_id = new Array();
$("#btn").on('click', function () {
    $("#show").append("<div><button type='button' id='btn1x' class='close pull-right' aria-hidden='true'>&times;</button>" + "<pre>button 1</pre></div>");

    product_id.push("btn1");
    alert(product_id);
});

$(document).on('click', 'button#btn1x', function () {
    $(this).parent().remove();
    alert(product_id);
    //when I click this button, i want to remove the "btn1" that I pushed a while ago from my array 
});


$("#btn2").on('click', function () {
    $("#show").append("<div><button type='button' id='btn2x' class='close pull-right' aria-hidden='true'>&times;</button>" + "<pre>button 2</pre></div>");

    product_id.push("btn2");

});

$(document).on('click', 'button#btn2x', function () {
    $(this).parent().remove();
    //when I click this button, i want to remove the "btn2" that I pushed a while ago from my array 
});

我想单击按钮,最终某个值将被插入到我创建的数组中。但是,我还创建了一个关闭按钮,当我单击它时,我想从数组中删除插入的值。

最佳答案

使用.pop(),所有常规的javascript函数都可以在jQuery中使用。
http://learn.jquery.com/javascript-101/arrays/

给定一个数组:

var array = [1,2,3,5];
array.push(9); // [1,2,3,5,9]
array.pop(); // [1,2,3,5]

现在,如果您想删除 2...那就不同了。

关于javascript - 如何使用javascript删除数组中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19391999/

相关文章:

arrays - 加快我的字符串文本替换代码

javascript - 如何让 eval 使用本地范围

javascript - 如何使用 React 在 Meteor 1.5.2 上进行分页?

javascript - 如何使用 KendoDetailInit 函数从另一个网格的不同行获取不同的网格作为子级

jquery.validate 非事件选项卡验证

javascript - Javascript 数组中的未定义值是否使用任何内存或在 for-in 循环中迭代?

javascript - 在元素属性中使用用户输入是否安全?

javascript - 在jsp中的jstree中的每个节点上添加可点击按钮

javascript - jQuery 单击不适用于动态创建的元素

javascript - 如何从纯javascript获取div的最长高度?