gpt4 book ai didi

javascript - 动态创建类名。仅

转载 作者:行者123 更新时间:2023-12-03 10:59:03 37 4
gpt4 key购买 nike

var i = 0;

function Myfunc() {
var newdiv = document.createElement('div');
var el = document.createElement('div');
var dynamicClass = "x" + i;
i++;
el.setAttribute('class', dynamicClass);
var c = document.getElementsByClassName(dynamicClass);
newdiv.appendChild(ele);
for (var j = 0; j < c.length; j++) {
c[j].appendChild(newdiv);
}
}
<input type="hidden" value="0" id="nextValue">
<div class="x1">a...</div>
<div class="x2">b...</div>
<div class="x3">c...</div>
<input type="button" onclick="Myfunc()" />

我想在函数中动态创建类名。根据我使用 Java 和 C 的经验,我希望每次按下按钮时都会触发函数来增加变量 i (又名更改类的名称,因为你会见下文)并将变量i的值保留到内存中,以便下次再次触发函数时可以进一步增加它。

function Myfunc(i) {
var newdiv = document.createElement('div');
var el = document.createElement('div');
var dynamicClass = "x" + i;
i++;
el.setAttribute('class', dynamicClass);
var c = document.getElementsByClassName(dynamicClass);

for(var j=0;j<c.length;j++){
newdiv.appendChild(el);
}
}
<div class="x1">a...</div>
<div class="x2">b...</div>

<div class="xn">c...</div>


<input type="button" onclick="Myfunc()"/>

变量i如何具有先前的值?如果我的问题听起来微不足道的话,我是一名学生,对 JS 的经验几乎为零。

最佳答案

刚刚在按钮本身上添加了数据属性,并将“this”传递给函数调用以获取按钮。无需维护全局变量或其他隐藏元素:http://jsfiddle.net/h0cuLuty/1/

JavaScript:

 function Myfunc(obj) {
var i=parseInt(obj.getAttribute('data'),10);
var existing = document.getElementsByClassName('parent')[0];
var el = document.createElement('div');
var txt = document.createTextNode("x"+i);
el.appendChild(txt);
var dynamicClass = "x" + i;
el.setAttribute('class',dynamicClass);
existing.appendChild(el);

i++;
obj.setAttribute('data',i);
}

HTML:

<div class="parent">
</div>

<input type="button" data="1" onclick="Myfunc(this)"/>

关于javascript - 动态创建类名。仅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28166096/

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