gpt4 book ai didi

javascript - 在某些事件上动态创建与之关联的 html 元素和对象

转载 作者:行者123 更新时间:2023-11-28 01:38:49 26 4
gpt4 key购买 nike

1.创建一个最初为空的主对象2.在按钮点击之类的某些事件上执行以下操作。3.创建一个元素并将该元素附加到容器(html body)。4.调用一个将为该元素动态创建对象的函数。5.将类等元素属性存储在元素对象中。

var main_info = { };
$("button").on("click", function(){
var element = '<div class="class1 class2 class3 class4"></div>';
$("body").append(element);
ele_info(element);
function ele_info(element){
var info = { };
info.class_arr = element.classList;
//how to push info object to main_info object.
}
});

如果我点击按钮 5 次,那么主体中将有 5 个元素。现在,如果我想知道第三个元素的属性,我应该如何选择该元素以及我应该如何访问元素对象属性?

最佳答案

1.create a main object which is empty initially

var main_info = [];

2.On some event like button clike perform the following. 3.create an element and append that element to the container(html body).

$("button").on("click", function() {});

var element = "<div>Here we go</div>";
$("body").append(element);

4.call a function that will dynamically create a object for that element.

function ele_info(elem) {}

5.store the element properties like class in the element object.

var info = {};
info.class_arr = $(elem).attr('class').split(/\s+/);
main_info.push(info);

最终代码将是这样

var main_info = [];
$("button").on("click", function() {
var element = "<div>Here we go</div>";
$("body").append(element);
var divs = $("div");
$(divs[divs.length - 1]).addClass("class1 class2 class3 class4");

ele_info($("div")[$("div").length - 1]);

function ele_info(elem) {
var info = {};
info.class_arr = $(elem).attr('class').split(/\s+/);
main_info.push(info);
console.log(main_info);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
<button>add</button>
</body>

访问添加的任何元素也是这样

console.log($("div")[2]);

从数组中:

console.log(main_info[2]);

关于javascript - 在某些事件上动态创建与之关联的 html 元素和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50541736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com