我有一个从CollectionType Symfony中检索id的javascript代码:
$(document).ready(function() {
$('.well').change(function () {
var day_n = document.getElementById('command_billet_billet_0_dateBirthday_day').value;
var month_n =
document.getElementById('command_billet_billet_0_dateBirthday_month').value;
var year_n =
document.getElementById('command_billet_billet_0_dateBirthday_year').value;
每次添加新表单时,此ID都将变为
document.getElementById('command_billet_billet_1_dateBirthday_day').value;
document.getElementById('command_billet_billet_1_dateBirthday_month').value;
document.getElementById('command_billet_billet_1_dateBirthday_year').value;
document.getElementById('command_billet_billet_2_dateBirthday_day').value;
document.getElementById('command_billet_billet_2_dateBirthday_month').value;
document.getElementById('command_billet_billet_2_dateBirthday_year').value;
号码更改和ID结束(日,月,年)
是否可以将getElementById中的javascript代码集成到获取所有数字并区分id的结尾?
答案 0 :(得分:0)
document.querySelectorAll()
可以做到。
var ps = document.querySelectorAll('[id^=id]');
console.log(ps);
for(i in ps){
ps[i].style.color = 'red';
}

<p id="id1A">Hello</p>
<p id="id2A">World</p>
<p id="id3A">Hello!</p>
&#13;
答案 1 :(得分:0)
(function(){
var digitReg = /\d+/;
var wells = document.querySelectorAll('.well');
for(var i = 0; i< wells.length; i++){
var id = wells[i].getAttribute('id');
console.log(id.match(digitReg)[0])
}
})()
<div class="well" id="command_billet_billet_1_dateBirthday_day"></div>
<div class="well" id="command_billet_billet_2_dateBirthday_day"></div>
答案 2 :(得分:0)
如果你可以改变你的html标记,那么你可以使用jQuery data()api
像这样:
$(function() {
$("#getIds").click(function() {
var ids = [];
$(".well").each(function() {
ids.push($(this).data("id"));
})
console.log(ids);
});
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well" data-id="1"> div Id 1</div>
<div class="well" data-id="2"> div Id 2</div>
<div class="well" data-id="3">div Id 3</div>
<div class="well" data-id="4"> div Id 4</div>
<div class="well" data-id="5">div Id 5</div>
<div class="well" data-id="6">div Id 6</div>
<button id="getIds" type="button">Get Ids</button>
&#13;