javascript - jQuery:如何创建每个项目有两个值的数组

标签 javascript jquery arrays

我是 jQuery 的新手,希望有人可以帮助我,并提供一个简短的解释,以便我将来可以将其应用于类似的情况。

我有一个动态构建的大型 HTML 页面。 该页面包含多个表格,其中具有某些可编辑的 div (contenteditable=true)。这些 div 都有类“editable”

现在我想为所有这些 div 创建一个数组,其中包含它们的 id 和内容(文本)。

到目前为止,我有以下内容应该为这些带有递增数字的 div 创建唯一的 id,但我不确定如何为此创建数组。 另外,出于好奇,是否有特定术语如何调用每个项目有两个值的此类数组?

我的 jQuery:

$('#btnSave').on('click', function(){
    var i = 0;
    $(this).closest('form').find('div.editable').each(function(){
        $(this).attr('id', 'ed' + i+1);
        if( ($(this).text != '') && ($(this).text != ' ') ){
            $(this).addClass('edited');
        }
        i++;
    });
});

// my attempt for the array (perhaps the wrong approach):
var arrEdited = new Array();
$('div.edited').each(function(){
    arrEdited.push($.trim($(this).text()));
});

提前非常感谢, 迈克

最佳答案

我认为您不需要另一个循环,而是可以将其放在第一个循环中,即 if( ($(this).text() != '') && ($(this). text() != ' ') ),然后将对象推送到数组而不是值。

var arrEdited = new Array();
$('#btnSave').on('click', function(){
    $(this).closest('form').find('div.editable').each(function(index){
        //you could use the index when you use .each function
        $(this).attr('id', 'ed' + (index+1));
        if( ($(this).text() != '') && ($(this).text() != ' ') ){
            $(this).addClass('edited');
            //instead of using another loop, you can put your code here
            arrEdited.push({
                id: $(this).attr('id'),
                text: $.trim($(this).text())
            });
            //here you use an object, people call it array of objects
        }
    });
});

关于javascript - jQuery:如何创建每个项目有两个值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30637747/

相关文章:

javascript - 检查样式是否为="height: 0px"

javascript - AngularJS 基于复选框选择显示数组

arrays - 在 D' 共享库和 Pascal (Lazarus) 主机之间发送/接收字符串和数组

javascript - 如何为每个四分之一圆添加点击事件

javascript - "TypeError: res.sendStatus is not a function"为什么我在一段时间后收到此错误?

javascript - 日期格式

Javascript 数组匹配复杂度较低

php - 如果图像标签是从数据库动态创建的,我如何使用 javascript 或 php 来确定何时加载图像?

javascript - 添加新数据后 ChartJS 图表出现错误

javascript - 如何将两个具有不同参数的函数的代码结合起来?