【问题标题】:Bind jquery UI date-picker on focus of input element将 jquery UI 日期选择器绑定在输入元素的焦点上
【发布时间】:2016-05-20 05:21:58
【问题描述】:

您好,我有一种情况,当输入元素被聚焦时,我需要绑定 jquery UI datepicker({}) 函数。我无法使用下面的代码实现它,所以请各位帮忙,我该如何绑定输入元素获得焦点时的 datepicker 函数

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
	<title> Jquery UI Date Picker </title>
</head>
<body>
   
    <input type="text" id="date" />

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    <script>
       //$('#date').datepicker({});
       $('#date').on('foucs',function(){
          $(this).datepicker({});
       });
    </script>
</body>
</html>

【问题讨论】:

  • 其实焦点的时候不需要datepicker,只需要设置input readonly,像这样:jsfiddle.net/ananis/sdq26rhs
  • 我必须在焦点上绑定功能

标签: jquery jquery-ui jquery-ui-datepicker


【解决方案1】:

您可以使用 onclick 事件打开日期选择器:

<input type="text" id="date" onclick="$('#date').datepicker();$('#date').datepicker('show');" />

$( "#date" ).focus(function() {
    $('#date').datepicker();
    $('#date').datepicker('show');
});

【讨论】:

  • 感谢您的快速回复。我无法访问输入元素,我只能在 jquery 中完成所有操作。有什么方法可以实现
  • ,这些输入元素是动态生成的,所以不会有任何id或类分配给它,例如我刚刚添加的目的。输入焦点元素上触发了一个回调函数,所以我只有在回调函数中使用 $(this) 的机会
  • 感谢 Dhara,但为什么在第一次聚焦时它不起作用。它只在第二次聚焦时起作用
  • 是第一次进入 .focus 事件吗?通过提醒尝试
  • alert 和 console.log() 适用于第一个焦点本身,我不知道为什么这个日期选择器不适用于第一个焦点。你能试试吗
【解决方案2】:

试试这个

$(function() {
  $("#datepicker").datepicker();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>Date:
  <input type="text" id="datepicker">
</p>

【讨论】:

    【解决方案3】:

    代码应该是:

    $( "#date" ).focus(function() {
        $( "#date" ).datepicker();
    });
    

    焦点参考:https://api.jquery.com/focus/ 日期选择器参考:https://jqueryui.com/datepicker/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多