简体   繁体   English

使用jQuery使用onkeypress创建输入?

[英]Creating input with onkeypress with jQuery?

I am trying to create a input element with a expected html output of this: 我正在尝试使用预期的html输出创建输入元素:

<input 
  type="text" 
  maxlength="13" 
  value="DD/MM/YY 00:00.0" 
  onkeypress="dateTime()"
>

I tried doing this with the following jQuery code 我尝试使用以下jQuery代码执行此操作

var input = $("<input>",
  {
    name : newName,
    maxlength : newSize,
    size : newSize,
    type : 'text',
    value : newVal,
    onkeypress : dateTime()
  });

But I don't get the expected output 但是我没有得到预期的输出

<input type="text" maxlength="13" value="DD/MM/YY 00:00.0">

Question 1 : what is the description of this code, because I cannot for the life of me find anything in the jQuery documentation about this stuff (link would be appreciated). 问题1:这段代码的描述是什么,因为我一生都无法在jQuery文档中找到有关此内容的任何内容(链接将不胜感激)。

Question 2 : what is the correct parameter to use to get my expected html result? 问题2:什么是用来获取预期的html结果的正确参数?

try 尝试

onkeypress : "dateTime()"

instead of 代替

onkeypress : dateTime()

that one executes the function. 那个执行功能。

var input = $("<input>",
  {
    name : newName,
    maxlength : newSize,
    size : newSize,
    type : 'text',
    value : newVal,
    onkeypress : dateTime
  });

or 要么

input.on('keypress',dateTime);

In the callback, "this" represents the event target (input). 在回调中,“ this”表示事件目标(输入)。

You can get values from the input by using $(this).val(); $(this).attr('myattribute'); $(this).data('myvar'); 您可以使用$(this).val(); $(this).attr('myattribute'); $(this).data('myvar');从输入中获取值$(this).val(); $(this).attr('myattribute'); $(this).data('myvar'); $(this).val(); $(this).attr('myattribute'); $(this).data('myvar');

Suggest you need to review the keypress docs on jquery: 建议您需要查看jquery上的keypress文档:

http://api.jquery.com/keypress/ http://api.jquery.com/keypress/

You need to look at how to use document ready event in jquery too and how the selector engine works. 您还需要查看如何在jquery中使用document ready事件以及选择器引擎如何工作。 Your code should look a bit like this: 您的代码应如下所示:

$(function() {
    $("input").keypress(function() {
         //do stuff
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM