我是 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/