javascript - 根据所选日期填写星期几
问题描述
我有一个表格,其中包含一个数据列和一个星期几在选择日期时,我希望该列根据所选数据填充日期名称
我正在尝试这样:
$('#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
:04-07-2019
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>
解决方案
您应该阅读上面的 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 事件委托......
同样在JS Fiddle上。
推荐阅读
- json - 如何从此 Json 数据中获取特定数据?
- ios - 如何在swiftUI中更改状态栏?
- carthage - 我可以告诉 Carthage 如何构建不使用 xcode 的项目吗?
- python - 如何从经验 cdf 计算和绘制 pdf?
- r - Roxygen2 文档参数乱序
- c# - 为什么我不能将表格调整到显示器的大小?(Windows 窗体)
- ibm-infosphere - 对于任何 ETL 或数据转换工具,IGC 是否允许我跟踪数据的来源或数据的使用方式?
- react-final-form - 提交后如何获取所有值 - 包括未触及的字段
- c# - 程序将无法按计划任务正常运行。手动执行程序运行良好
- ios - 我可以在我的 Mac Catalyst iOS 应用程序上禁用窗口大小调整功能吗