<div id="numbers">
<button>7</button>
<button>8</button>
<button>9</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button class="colspan">0</button>
<button>,</button>
</div>
<div id="operators">
<button>/</button>
<button>←</button>
<button>*</button>
<button>C</button>
<button>-</button>
<button>+</button>
我正在寻找一种解决方案,让这更容易。 我希望我可以通过jquery设置按钮ID和Class。
怎么做? 使用$('#numbers')。append不起作用。
答案 0 :(得分:0)
尝试
$('#numbers').children("button").addClass("hello");
答案 1 :(得分:0)
您可以这样做:
var numbers = [7,8,9,4,5,6,1,2,3];
var ops = ['/','*','C','-','+'];
var count
numbers.forEach(function(num){
$("#numbers").append("<button id=" +num+ " class=" +num+ ">"+num+"</button>");
});
ops.forEach(function(val){
$("#numbers").append("<button id=" +val+ " class=" +val+ ">"+val+"</button>");
});
然后将CSS添加到3个组中的组按钮中。
<强> DEMO 强>
如果您想从按钮文字中添加数字,请执行以下操作:
$("#numbers").children("button").each(function(){
$(this).attr("id","no"+$(this).text());
$(this).attr("class","no"+$(this).text());
});
$("#operands").children("button").each(function(){
$(this).attr("id","op"+$(this).text());
$(this).attr("class","no"+$(this).text());
});
<强> DEMO 强>
答案 2 :(得分:0)
如果我理解正确,你想给每个按钮一个唯一的&#34; id&#34;,这段代码为#number
的孩子生成ID,模式为&#34; no1&#34 ; ,&#34; no2&#34;等,以及#operators
&#34; op1&#34; ,&#34; op2&#34;等等。
var id=1;
$('#numbers').children('button').each(function(){
$(this).attr('id','no'+id);
id++;
});
id=1;
$('#operators').children('button').each(function(){
$(this).attr('id','op'+id);
id++;
});
答案 3 :(得分:0)
使用addClass()
为特定元素提供类名。
您可以使用attr("key","value")
方法提供ID。
$("#numbers button").each(function () {
var obj = $(this);
obj.addClass(obj.text());
obj.attr("id", obj.text());
});
答案 4 :(得分:0)
我相信你想要的东西如下:
$("#numbers button").each(function(){
$(this).addClass("class-name");
$(this).attr("id", $(this).text()");
//if you want to set the id equals the button text
});
对于运营商,只需将$("#numbers button")
更改为$("#operators button")
..