如何将日期选择器添加到可编辑内容的TD中?

时间:2018-06-29 09:49:45

标签: javascript jquery

以下是我的代码:

var j = jQuery.noConflict();
j(".datetimepicker").click(function() {
  j(".datetimepicker").datepicker({
    dateFormat: 'dd-mm-yy',
    onClose: function(dateText, inst) {
      // When the date is selected, copy the value in the content editable div.
      // If you don't need to do anything on the blur or focus event of the content editable div, you don't need to trigger them as I do in the line below.
      $(this).parent().find('.datetimepicker').focus().html(dateText).blur();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<tr>
  <th>First Date</th>
  <td class='datetimepicker' contenteditable='true'>"+ paidDate1 + "</td>
</tr>

因此,当我单击该行时,内容是可编辑的,但日期选择器未显示。我怎样才能解决这个问题?

2 个答案:

答案 0 :(得分:1)

AFAIK您不能将datepicker<td>一起使用,因此有一种方法可以将内容替换为<input>

如果那不是您想要的,请原谅我。

var newDate = new Date();
var paidDate1 = newDate.getFullYear() + "/" + ('0' + (newDate.getMonth() + 1)).slice(-2) + "/" + ('0' + newDate.getDay()).slice(-2);

var tr = "<tr><th>First Date</th><td>" + paidDate1 + "</td></tr>";

$('#t').append(tr);

// to avoid twice click on td;
$("#t").on('click.input', 'input', function(event) {
    event.stopPropagation();
})

$("#t").on('click.td', 'td', function() {
    var $td = $(this);
    var text = $(this).html();
    var $input = $('<input class="datetimepicker" value="' + text + '"/>');
    $td.html('').append($input);

    $input.datepicker({
        dateFormat: 'dd-mm-yy',
        onClose: function(dateText, inst) {
            $td.html(dateText.split('-').reverse().join('/'));
            $td.attr('disabled', false);
        }
    }).datepicker('show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<table id="t"></table>

答案 1 :(得分:-3)

您尝试使用j(document).find('td.datetimepicker')吗?当您尝试仅按类选择时,表的行为很奇怪。