[英]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.