我有一个表,其中一个数据列对应一周中的另一天 选择日期时,我希望该列根据所选数据将日期填入日期
我正在尝试这样:
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable ><input type="date" class="data1" id="data1"/></td>';
html += '<td><input type="text" class="data2" id="data2"/></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-send"></span></button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html); //<--- right here
});
$(document).ready(function(){
var semana = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"];
$(".data1").on(function(){
var data = this.value;
var arr = data.split("-").reverse();
var teste = new Date(arr[0], arr[1] - 1, arr[2]);
var dia = teste.getDay();
$(".data2").val();
});
});
,但在设置日期时不显示警报。
日期的格式为input type = date
:2019年4月7日
HTML:
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info"><span class="glyphicon glyphicon-plus"></span></button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Data</th>
<th>Dia da Semana</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
答案 0 :(得分:1)
您应该阅读上面的ADyson注释,因此对代码进行了一些更改。一些简单的例子是:
var daysInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
$('#add').click(function() {
var html = '<tr>';
html += ' <td><input type="date" class="input-date" /></td>';
html += ' <td><input type="text" class="input-day" /></td>';
html += ' <td><button type="button" class="button-insert">Insert</button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
$("body").on('change', '.input-date', function(e) {
var thisDate = $(this);
var data = thisDate.val();
var teste = new Date(data);
var dia = teste.getDay();
var closestRow = thisDate.closest('tr');
closestRow.find('.input-day').val(daysInWeek[dia]);
});
$("body").on('click', '.button-insert', function(e) {
var thisButton = $(this);
var closestRow = thisButton.closest('tr');
/* Do whatever you want */
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button type="button" id="add">Add</button>
</div>
<table id="user_data">
<thead>
<tr>
<th>Data</th>
<th>Dia da Semana</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
因此,没有重复的ID,第二个jQuery event delegation ...
也在JS Fiddle上。