onkeyup 或 onkeypress javascript 事件问题 - 密码状态更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8662513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:09:37  来源:igfitidea点击:

onkeyup or onkeypress javascript event issue - password status updates

javascripteventskeyboard-events

提问by PerryCS

Programming Question First(from w3 schools)

编程问题第一(来自w3学校)

The programming example way below (from W3 schools) is nice and easy, it works on their website but I'm really confused on something.

下面的编程示例方式(来自 W3 学校)既简单又好用,它可以在他们的网站上使用,但我真的很困惑。

onkeypress="return noNumbers(event)"

why is there a return before the function? What does it do? If you know the answer to that - how did you find out that information? My guess would be, that it allows the keypressed function to continue processing the keystroke since my event "interupted" it?

为什么在函数之前有一个返回?它有什么作用?如果你知道答案——你是如何找到这些信息的?我的猜测是,它允许按键功能继续处理按键,因为我的事件“中断”了它?

also- I have been trying to see what 'event' is. It doesnt seem to be a keyword. I spent > hour trying to find what it is. It doesnt seem to be assigned anywhere in their code example. Normally in that spot you would see 'this'. If it's a not assigned variable will it always pass the event handler? Confused...

另外- 我一直在试图了解“事件”是什么。好像不是关键词。我花了 > 小时试图找到它是什么。它似乎没有在他们的代码示例中的任何地方分配。通常在那个地方你会看到“这个”。如果它是一个未分配的变量,它是否总是通过事件处理程序?使困惑...

What I want to do with their function

我想用它们的功能做什么

I want to make a password strength checker AS you type. I was looking at their example so I could figure out how to capture keys (cross browser and minimal IE7). My idea was...

我想在您键入时制作密码强度检查器。我正在查看他们的示例,因此我可以弄清楚如何捕获密钥(跨浏览器和最小的 IE7)。我的想法是...

<input type="password" name="pword" maxlength="50" size="50" id="field_pword" onkeyup="PasswordStrength(name, 8, 'relaxed')" onblur="CheckField(name, 8, 1)">

note:Yes, I know it's better to assign event handlers outside of the html but I couldn't see a way to pass variables to it unless it was inline. I'm a novice so I may have overlooked something but... thats why I do it IN the HTML.

注意:是的,我知道最好在 html 之外分配事件处理程序,但我看不到将变量传递给它的方法,除非它是内联的。我是新手,所以我可能忽略了一些东西,但是......这就是我在 HTML 中这样做的原因。

also, IS IT BAD how I am passing name? it does send pword to the function but am I doing something wrong there? Should I just make it a constant string? It works as is, but sometimes just because something works... doesn't mean it's correct. :)

另外,我传递名字的方式不好吗?它确实将 pword 发送到该函数,但我在那里做错了什么吗?我应该让它成为一个常量字符串吗?它按原样工作,但有时仅仅因为某些东西有效......并不意味着它是正确的。:)

onkeyup="PasswordStrength('pword', 8, 'relaxed')" onblur="CheckField('pword', 8, 1)">

My checkfield function works (I use it after every field) I recently added in PasswordStrength. My question is... my new function isn't passing the event hander so how can I check what key is pressed? Can I do this?

我最近在 PasswordStrength 中添加的检查字段功能有效(我在每个字段之后使用它)。我的问题是……我的新函数没有通过事件处理程序,所以我如何检查按下了什么键?我可以这样做吗?

onkeyup="PasswordStrength(name, 8, 'relaxed', event)"

or should it read...

或者应该读...

onkeyup="return PasswordStrength(name, 8, 'relaxed', event)"

If I can't pass whatever 'event' is that way, inside my function can I accurately get what the key pressed was without a big mess of code? Since I'm learning I need examples to be as simple as possible (please).

如果我不能以这种方式传递任何“事件”,那么在我的函数中,我能否准确地获得按下的键,而无需大量代码?由于我正在学习,因此我需要示例尽可能简单(请)。

Using my function I was going to do it this way but I still don't know how to get what key was pressed...

使用我的功能,我打算这样做,但我仍然不知道如何获得按下的键......

function PasswordStrength(sField, iMinLength, sStrength, e?)
{
var form = document.forms[0];
var gc = form[sField].value;
    // once I have the value I can do checking but it would be nice to have WHAT key
    // was pressed
    // the e? above is where I was thinking of passing the event

W3 example I was pulling some knowledge from...

W3 示例我从...中提取了一些知识

function noNumbers(e)
{
var keynum;
var keychar;
var numcheck;

if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
numcheck = /\d/;
return !numcheck.test(keychar);
}
</script>

<form>
Type some text (numbers not allowed):
<input type="text" onkeypress="return noNumbers(event)" />
</form>

</body>
</html>

As someone is typing I was going to change the text using innerHTML beside the password field to say, "Weak", "Ok", "Good", "Perfect" or something along those lines for the password status. I'd love to do it how google does it with a graphic to the left of the field but I don't know how to do that simply. lol.

当有人打字时,我打算使用密码字段旁边的 innerHTML 更改文本,说“弱”、“好”、“好”、“完美”或类似密码状态的内容。我很想用谷歌在字段左侧的图形来做它,但我不知道如何简单地做到这一点。哈哈。

Is my way fixable? Do you have a better way to do this that I don't know about? Much appreciated. Awaiting an infusion of wisdom...

我的方法可以解决吗?你有没有更好的方法来做到这一点,我不知道?非常感激。等待智慧的注入……

采纳答案by Niet the Dark Absol

1) The "return" word makes it so that if the function returns false, that gets passed back to the event and stops the keystroke from being processed by the browser (and appearing in the input field if that's what the event is on).

1)“返回”字使得如果函数返回false,它会被传递回事件并停止浏览器处理击键(如果事件发生,则出现在输入字段中)。

2) eventis the Event object, which contains information on the event such as what key wa pressed, where the event was fired, etc.

2)event是 Event 对象,它包含有关事件的信息,例如按下了什么键,事件在何处触发等。

3) Yes, it is bad how you are passing name, because you aren't passing it. Use this.nameinstead.

3)是的,你通过的方式很糟糕name,因为你没有通过它。使用this.name来代替。

4) In this case, you don't need returnbecause you aren't trying to stop a keystroke from being added to the textbox. Similarly, you don't need to pass eventbecause you can pass this.valueto get the contents of the textbox.

4) 在这种情况下,您不需要,return因为您不想阻止将击键添加到文本框。同样,也不需要pass,event因为可以passthis.value得到textbox的内容。

5) You can just pass thisinstead of this.name, this.valueor whatever other values.Then, in the function, get the properties from the single argument.

5)您可以只传递this而不是this.namethis.value或任何其他值。然后,在函数中,从单个参数中获取属性。

6) Once you pass the entire value with this.value, you can run your tests on that. There is absolutely no need to know what key was pressed, especially as things like Ctrl+Vwould completely screw you over.

6) 一旦你用 传递了整个值this.value,你就可以在上面运行你的测试。绝对没有必要知道按下了什么键,尤其是像Ctrl+V这样的事情会完全把你搞砸。

7) You can have a <div>and change its width and/or background colour to make a sort of strength bar indicator.

7) 您可以使用 a<div>并更改其宽度和/或背景颜色来制作一种强度条指示器。

回答by Matmarbon

Just to your first programming questions:

就你的第一个编程问题:

  • Your suggestion is right, to return a value inside of an event lets you interrupt the action depending on the values content. Returning falseinside onclickwill end in the click not to be done. So <a href="http://test.de" onclick="return false;">linkname</a>wont link you to anything if JavaScript is active.
  • eventis simply a variable declared before it runs into the actual event, further explanation below.
  • 您的建议是正确的,在事件中返回一个值可以让您根据值的内容中断操作。返回false内部onclick将以单击未完成结束。因此<a href="http://test.de" onclick="return false;">linkname</a>,如果 JavaScript 处于活动状态,则不会将您链接到任何内容。
  • event只是一个在它运行到实际事件之前声明的变量,下面进一步解释。

You know the elements eventhandler attributes in JavaScript? They are functions i.e.

您知道 JavaScript 中的元素 eventhandler 属性吗?它们是函数,即

document.createElement('div').onclick = function( event ){
  //do something...
  return true || false;
};

if you assign an onclickattribute to a tag it's simply another adjusted way to create this anonymous function. So

如果您onclick为标签分配一个属性,这只是创建此匿名函数的另一种调整方式。所以

<input onclick="this.value = 'can\'t click me :P Mouse X: ' + event.clientX; return false;" type="text" id="ip" />

will behave as if you created an anonymous function taking the argument event.

将表现得好像您创建了一个带参数的匿名函数event

window.onload = function(){
  document.getElementById('ip').onclick = function( event ){
    this.value = 'can\'t click me :P Mouse X: ' + event.clientX; return false;
  };
};

This will behave exactly equal except of the delayed assignment.

除了延迟分配之外,这将完全相同。

The thiskeyword is always the owner object whose property function you're accessing or the object you're passing to an apply/callmethod. In this case it's obviously the owner - the DOM element. So this.valueis the inputs value.

this关键字总是所有者对象其属性功能,你所访问或对象要传递到apply/call方法。在这种情况下,它显然是所有者 - DOM 元素。s 值this.value也是如此input

The eventpassed to the function is just an object containing some useful information about the current browsers state and miscellaneous. It's having slightly different properties filled with different values in different browsers but the main functionality is the same everywhere.

event传递给函数仅仅是包含有关当前的浏览器状态和杂项一些有用的信息的对象。它的属性略有不同,在不同的浏览器中填充了不同的值,但主要功能在任何地方都是相同的。

  • As explained above it makes no difference whether you write what you did or this:
  • 如上所述,无论您写的是您所做的还是这样的,都没有区别:
window.onload = function(){
  var yourElement = document.getElementsByTagName('pword')[0];
  yourElement.onkeyup = function( event ){
    PasswordStrength(this.name, 8, 'relaxed')
  };
};
  • No it's not really badto use just name.. whenever you access a property of the owners object you can omit the thiskeyword. Thus it's simply the same conflict as the one about writing
  • 不,仅使用..并不是很糟糕name每当您访问所有者对象的属性时,您都可以省略this关键字。因此,这与写作的冲突完全相同
<script type="text/javascript">//<![CDATA[
 onload = function(){ alert('hello!') };
//]]></script>

instead of window.onloador this.onloador even this.window.onload(which are all theoretically working since the everything containing object has a property named windowwhich refers to itself). You could say it's a matter of convention. But since the convention to always access own properties over the thiskeyword (except for windowwhich you should access over its property window) is strongly established and supported, you probably should write this.name.

代替window.onload或者this.onload甚至this.window.onload(这都是理论上的工作,因为包含对象的任何事物都有一个命名的属性window是指本身)。你可以说这是一个约定俗成的问题。但是由于始终通过this关键字访问自己的属性的约定(除了window您应该通过其属性访问的属性window)已得到强有力的建立和支持,您可能应该编写this.name.

  • That depends on whether you want to eventually interrupt the event and don't let the user finish his keyup. Explained above.
  • Why shouldn't you be able to pass the eventobject? Just treat it like a normal variable.
  • Combining the information above and the example in your question you should be able to get knowledge about which key was pressed.
  • 这取决于您是否希望最终中断事件并且不让用户完成他的keyup. 上面解释了。
  • 为什么不能传递event对象?只需将其视为普通变量即可。
  • 结合上述信息和问题中的示例,您应该能够了解按下了哪个键。