简体   繁体   English

如何将HTML中的Javascript事件处理程序内联转换为要参数化的?

[英]How do I convert a Javascript event handler inline in HTML to be parameterized?

Quick javascript question. 快速的JavaScript问题。 I am creating a simple script where a form field entry disappears/reappears using onfocus and onblur. 我正在创建一个简单的脚本,其中使用onfocus和onblur在表单字段条目消失/重新出现。

I'm wondering why the following inline script works: 我想知道为什么以下内联脚本有效:

<div>
<input type="text" name="email" id="email" value="Requires validation"
onfocus="if(this.value == 'Requires validation'){this.value = '';}"
onblur="formappear()">
</div>

and the following script with a parameterized function doesn't: 而以下带有参数化功能的脚本则没有:

<head>
<script type='text/javascript'>
function formclear(field) {

if (field.value == "Requires validation") {
field.value = "";
}

}
</script>
</head>
<body>
<div>
<input type="text" name="email" id="email" value="Requires validation"
onfocus="formclear(this.id)" onblur="formappear()">
</div>
</body>

I appreciate any responses in advance, I'm sure it's a simple mistake I'm making. 感谢您提前做出的任何回应,我敢肯定这是我犯的一个简单错误。

Dont pass in this.id , just pass in this 不要传递this.id ,只需传递this

<input type="text" name="email" id="email" value="Requires validation" onfocus="formclear(this)" onblur="formappear()">

Demo: http://jsfiddle.net/se6wm/ 演示: http//jsfiddle.net/se6wm/

You were passing in the id of the input, so when you were using field.value it was actually trying to do email.value which doesn't exist. 您正在传递输入的id ,因此当您使用field.value它实际上是在尝试执行不存在的email.value

因为您传递的是id而不是this

pass a value as formclear(this) instead of formclear(this.id) 将值传递为formclear(this)而不是formclear(this.id)

<input type="text" name="email" id="email" value="Requires validation"
onfocus="formclear(this)" onblur="formappear()">

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

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