Я хочу установить значение времени из javascript при нажатии таблицы tr, но это работает только в первой строке. тогда, если я попытаюсь предупредить (не установить значение) его рабочий идентификатор, в чем проблема, вот мой код:
Примечание: код таблицы слишком длинный, поэтому я не могу поделиться, но идентификатор таблицы — example_table.
Я надеюсь, что значение времени можно установить каждый щелчок по любой строке таблицы
$(document).ready(function() {
$("#example_table").delegate("tr", "click", function() {
var d = new Date(),
h = (d.getHours() < 10 ? '0' : '') + d.getHours(),
m = (d.getMinutes() < 10 ? '0' : '') + d.getMinutes();
now = h + ':' + m;
$("#start").val(now);
});
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type = "time" name = "start" class = "form-control form-control-border" id = "start">
Было бы здорово иметь минимальный воспроизводимый пример как минимум с 3 строками.
.delegate
устарел для .on
$(function() {
$("#example_table").on("click", "tr", function() {
$(this).find(".start").val(new Date().toISOString().slice(11, 16));
});
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id = "example_table">
<tr>
<td>Click on the row</td>
<td><input type = "time" name = "start" class = "form-control form-control-border start"></td>
</tr>
<tr>
<td>Click on the row</td>
<td><input type = "time" name = "start" class = "form-control form-control-border start"></td>
</tr>
<tr>
<td>Click on the row</td>
<td><input type = "time" name = "start" class = "form-control form-control-border start"></td>
</tr>
</tbody>
</table>
Если у вас есть кнопка в одной ячейке и время в другой, вы можете использовать closest для перехода к строке, а затем к вводу:
$(function() {
$("#example_table").on("click", ".now", function() {
$(this).closest("tr").find(".start").val(new Date().toISOString().slice(11, 16));
});
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id = "example_table">
<tr>
<td><button type = "button" class = "now">Now</button></td>
<td><input type = "time" name = "start" class = "form-control form-control-border start"></td>
</tr>
<tr>
<td><button type = "button" class = "now">Now</button></td>
<td><input type = "time" name = "start" class = "form-control form-control-border start"></td>
</tr>
<tr>
<td><button type = "button" class = "now">Now</button></td>
<td><input type = "time" name = "start" class = "form-control form-control-border start"></td>
</tr>
</tbody>
</table>
Вы не можете использовать один и тот же идентификатор для нескольких элементов, либо изменить его на класс, либо использовать уникальные идентификаторы для start, предполагая, что у вас есть один и тот же идентификатор для нескольких входов на разных trs.