Javascript 通过Jquery按钮选择并操作它们
我正在寻找一个解决方案,使这更容易。 我希望我可以通过jquery设置按钮ID和类 怎么做? 使用$'numbers'。追加不起作用。试试看Javascript 通过Jquery按钮选择并操作它们,javascript,jquery,html,Javascript,Jquery,Html,我正在寻找一个解决方案,使这更容易。 我希望我可以通过jquery设置按钮ID和类 怎么做? 使用$'numbers'。追加不起作用。试试看 <div id="numbers"> <button>7</button> <button>8</button> <button>9</button> <button>4</butto
<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>
您可以这样做:
$('#numbers').children("button").addClass("hello");
如果我理解正确,您希望给每个按钮一个唯一的id,这段代码为数字的子项生成no1、no2等模式的id,并为运算符op1、op2等生成id
$("#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());
});
使用addClass为特定元素指定类名
您可以使用attrkey、value方法来提供id
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++;
});
我相信你想要的东西如下:
$("#numbers button").each(function () {
var obj = $(this);
obj.addClass(obj.text());
obj.attr("id", obj.text());
});
对于操作员,只需将$numbers按钮更改为$operators按钮即可。您能解释更多吗?问题不是很清楚你在问什么?如何以编程方式给每个按钮一个唯一的ID?我需要通过jQuery给所有按钮一个其他ID“其他ID”是什么意思?随机的?一个根据特定的模式?什么?太好了,但我有个问题,看看我的JSFIDLE现在是双钮扣我明天可以做我没有15个Repu,今天我接受你的答案:
$("#numbers button").each(function () {
var obj = $(this);
obj.addClass(obj.text());
obj.attr("id", obj.text());
});
$("#numbers button").each(function(){
$(this).addClass("class-name");
$(this).attr("id", $(this).text()");
//if you want to set the id equals the button text
});