我正在编写一个脚本,该脚本将循环执行类似于以下内容的内容
$( document ).ready(function() {
let myObj = {};
initLoop();
function initLoop(){ //this loads the initial frames into the object
$('.looper').each(function(i, e){
var attr1 = $(this).attr('attr1');
var attr2 = $(this).attr('attr2');
var attr3 = $(this).attr('attr3');
var contents = $(this).html();
myObj[attr1][attr2][attr3] = contents;
});
}
});
我正在循环访问一组像这样结构的 div...
<div class="looper" attr1="1" attr2="1" attr3="1">content</div>
<div class="looper" attr1="1" attr2="1" attr3="2">content</div>
<div class="looper" attr1="1" attr2="1" attr3="3">content</div>
<div class="looper" attr1="1" attr2="2" attr3="1">content</div>
<div class="looper" attr1="1" attr2="2" attr3="2">content</div>
<div class="looper" attr1="1" attr2="2" attr3="3">content</div>
<div class="looper" attr1="1" attr2="3" attr3="1">content</div>
<div class="looper" attr1="1" attr2="3" attr3="2">content</div>
<div class="looper" attr1="1" attr2="3" attr3="3">content</div>
我收到错误
jQuery.Deferred exception: Cannot read properties of undefined (reading '1') TypeError: Cannot read properties of undefined (reading '1')
我有点不明白为什么这不起作用。有人可以建议任何更改吗?
我认为
myObj
没有 '1'
字段。
所以,
myObj[attr1]
是 undefined
。
结果,
myObj[attr1][attr2]
产生错误。
我在下面添加了一些示例代码。
希望能帮到你哪怕一点点。
...
$(".looper").each(function (i, e) {
var attr1 = $(this).attr("attr1");
var attr2 = $(this).attr("attr2");
var attr3 = $(this).attr("attr3");
((myObj[attr1] ??= {})[attr2] ??= {})[attr3] = $(this).html();
});
...