问题
How I dynamically add an id value for a canvas object in jQuery?
HTML
<div id="obj">
<canvas></canvas>
<canvas></canvas>
</div>
How do I change the second canvas object value with somename?
Expected result:
<canvas id="somename"></canvas>
回答1:
The $() function returns an array of matching DOM elements so you can just assign to the id property of the second element:
$('#obj canvas')[1].id = 'somename';
回答2:
Try this:
$("#obj canvas").slice(1).attr("id","somename");
来源:https://stackoverflow.com/questions/4976625/add-an-id-value-for-a-canvas-element-in-jquery