如何通过循环为30个按命名规则的元素绑定datetimepicker?
Got it, let's fix that loop issue for your datetimepicker bindings. The problem with most naive loops here usually comes down to variable scope or not properly targeting each element within the DOM-ready handler. Here are a few solid approaches to get this working:
方法1:使用ES6 let 的for循环(推荐,简洁直观)
直接在DOM就绪函数里写循环,用let来确保 each iteration gets its own independent variable scope:
var dateToday = new Date(); $(function() { // Loop from 1 to 30 for (let i = 1; i <= 30; i++) { $(`#Test${i}`).datetimepicker({ dateFormat: "dd-mm-yy", numberOfMonths: 1, stepMinute: 15, timeFormat: "hh:mm TT", minDate: dateToday }); } });
Why this works: Using let for the loop variable creates a new binding of i for every iteration. This means each datetimepicker initialization uses the correct index value instead of all pointing to the final value of i (31, which doesn't exist) after the loop finishes.
方法2:使用jQuery的.each()遍历匹配元素
If your elements all follow the TestX naming pattern, you can use an attribute selector to batch-select them and handle each one individually:
var dateToday = new Date(); $(function() { // Select all elements with ID starting with "Test" $('[id^="Test"]').each(function() { $(this).datetimepicker({ dateFormat: "dd-mm-yy", numberOfMonths: 1, stepMinute: 15, timeFormat: "hh:mm TT", minDate: dateToday }); }); });
Why this works: The [id^="Test"] selector grabs every element whose ID starts with "Test", no matter how many there are. The .each() method then processes each element one by one, with $(this) referencing the current element in the loop. This is more flexible if you ever need to add/remove elements later.
方法3:兼容旧环境的立即执行函数(if ES6 isn't available)
If your project is stuck in an older JS environment that doesn't support let, use an Immediately Invoked Function Expression (IIFE) to create a separate scope per iteration:
var dateToday = new Date(); $(function() { for (var i = 1; i <= 30; i++) { // Wrap in IIFE to preserve the current value of i (function(currentIndex) { $(`#Test${currentIndex}`).datetimepicker({ dateFormat: "dd-mm-yy", numberOfMonths: 1, stepMinute: 15, timeFormat: "hh:mm TT", minDate: dateToday }); })(i); } });
Why this works: The IIFE captures the current value of i as currentIndex for each loop iteration, ensuring each datetimepicker uses the correct index instead of sharing the final i value.
Why your original loop probably failed
If you used var i without handling scope, all your datetimepicker initializations would share the same i variable. By the time the loop finished, i would be 31, so you'd be trying to bind to a non-existent #Test31 element instead of the 30 valid ones.
内容的提问来源于stack exchange,提问作者MailBlade

