[英]Jquery problems with calling a function
所以我正在尝试创建一个函数,设置/删除字段中的水印,我已经开始工作了,输入的 html 元素如下所示:
<input type="text" name="pollName" id="pollName" value="DD-MM-YYYY" onfocus="javascript: watermark(this,true,'DD-MM-YYYY')" onblur="javascript: watermark(this,false,'DD-MM-YYYY')" >
然而,这很长,我正在尝试将代码移至 javascript,我打算在其中使用以下代码:
function watermark(dom,isFocus,watermark)
{
if(isFocus)
{
if(dom.value === watermark)
{
dom.value = "";
}
}
else if(!isFocus)
{
if(dom.value === '')
{
dom.value = watermark;
}
}
}
document.ready(function(){
$('#addOption').click(addOption);
$('.dateSelector').focusin(watermark(this,1,'DD-MM-YYYY'));
$('.dateSelector').focusout(watermark(this,0,'DD-MM-YYYY'));
});
这是有问题的 HTML。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>SPS: Create a new poll</title>
<link href="styles/stylePollCreator.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jsPollCretor.js"></script>
</head>
<body>
<div id="pollSetup">
<form action="" method="post">
<label for="pollName:">Poll name</label>
<input type="text" name="pollName" id="pollName" />
<br />
<label for="startDate">Start date: </label>
<br />
<input type="text" id="startDate" name="startDate" class="dateSelector" value="DD-MM-YYYY"/>
<label for="endDate">End date: </label>
<input type="text" id="endDate" name="endDate" class="dateSelector" value="DD-MM-YYYY"/>
<br />
<div id="pollOptions">
</div>
<input id="submitNewPoll" value="Create poll" type="submit" />
</form>
<button id="addOption">Add option</button>
</div>
</body>
</html>
addOption 函数工作正常,但是水印函数似乎在站点首次加载时调用一次,然后不再调用:/
感谢您的时间 :)
focusin
和focusout
期望参数的函数,并且您在技术上传递undefined
,因为水印不返回任何内容。 换句话说,您传递的是watermark
的结果,而不是watermark
本身。
所以,你想这样做:
$('.dateSelector').focusin(function(){watermark(this,1,'DD-MM-YYYY')});
编辑:
我同意上面的评论,您应该使用占位符属性。 因此,您的输入将如下所示:
<input type="text" name="pollName" id="pollName" placeholder="DD-MM-YYYY">
请记住,这是一个 HTML5 属性,因此对于旧浏览器,您必须使用 polyfill,但如果您使用google placeholder polyfill ,您会发现可以使用一百万个 polyfill。
然而,水印功能似乎在网站首次加载时调用一次
是的,这就是你正在做的
$('.dateSelector').focusin(watermark(this,1,'DD-MM-YYYY'));
$('.dateSelector').focusout(watermark(this,0,'DD-MM-YYYY'));
这相当于
watermark(this,1,'DD-MM-YYYY');
$('.dateSelector').focusin(undefined);
watermark(this,0,'DD-MM-YYYY');
$('.dateSelector').focusout(undefined);
将函数传递给事件注册:
$('.dateSelector').focusin(function(e) {
watermark(this,1,'DD-MM-YYYY');
}).focusout(function(e) {
watermark(this,0,'DD-MM-YYYY');
});
但是,正如@MattBall 已经评论过的,如果您需要支持旧浏览器,您应该只使用placeholder
属性并填充它(使用现有库):
<input type="text" name="pollName" id="pollName" placeholder="DD-MM-YYYY">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.