for (var i = 0; i < animals.length; i++) {
btn = $("<button>");
btn.attr("class", "btn");
btn.attr("value", animals[i]);
btn.text(celebrities[i]);
console.log(btn.value);
$("#animals").append(btn);
}
控制台日志btn.value返回未定义。我在做什么错了?
答案 0 :(得分:1)
按钮没有值属性,这样可以使用data-value为按钮设置属性。另外,您错误设置了btn = $("<button>");
btn = $("button");
btn.attr("class", "btn");
btn.attr("data-value", "Test Value");
btn.text("Text");
console.log(btn.text());
console.log(btn.data("value"));
btn = $("button");
btn.attr("class", "btn");
btn.attr("data-value", "Test Value");
btn.text("Text");
console.log(btn.text());
console.log(btn.data("value"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button></button>
答案 1 :(得分:0)
如果您想做的是纯JS,请执行以下步骤。
1)使用文档的createElement函数创建一个元素。通过此功能,您可以创建任何HTML / OWN元素之王
2)用户setAttribute函数,用于设置属性
3)将元素追加到文档的父元素中
var animals = ['tiger','dingo','panther']
var celebrities = ['cel1 1','cel 2','cel 3']
for (var i = 0; i < animals.length; i++) {
btn = document.createElement('button');
btn.setAttribute("class", "btn");
//btn.setAttribute("onclick","clickfunction");
btn.setAttribute("value", animals[i]);
btn.innderText = celebrities[i];
console.log(btn.value);
document.getElementById("animals").append(btn);
}