出于某种原因,onblur和onfocus属性不起作用。我定义它们了吗?
var replyTxt = document.createElement("input");
replyTxt.id="replyTxt";
replyTxt.type="text";
replyTxt.value="Write a reply";
replyTxt.onfocus = function(){if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';};
replyTxt.onblur= function(){if(replyTxt.value=='') replyTxt.value=replyTxt.defaultValue;};
我也尝试将"function(){if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';}"
放入引号
答案 0 :(得分:2)
事件有效 - 因此您的逻辑可能存在问题......
if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';
你在哪里设置replyTxt.defaultValue?在你的例子中,你没有 - 所以逻辑永远不会触发。试试这个......
var replyTxtDefaultText = "Write a reply";
var replyTxt = document.createElement("input");
replyTxt.id="replyTxt";
replyTxt.type="text";
replyTxt.value=replyTxtDefaultText;
replyTxt.onfocus = function(){if(replyTxt.value==replyTxtDefaultText) replyTxt.value='';};
replyTxt.onblur= function(){if(replyTxt.value=='') replyTxt.value=replyTxtDefaultText;};
答案 1 :(得分:1)
只是一个提示:
尝试在事件功能中将replyTxt
替换为this
。
答案 2 :(得分:0)
尝试setAttribute
。有关函数的更多信息,请查看此link
var replyTxt = document.createElement("input");
replyTxt.setAttribute('onFocus', 'focusFunction()');
function focusFunction()
{
if(replyTxt.value==replyTxtDefaultText)
replyTxt.value='';
}
答案 3 :(得分:0)
并确保将其附加到某物上。
<form id="x">
</form>
<script>
window.onload=function() {
var replyTxt = document.createElement("input");
replyTxt.id="replyTxt";
replyTxt.type="text";
replyTxt.value=replyTxt.defaultValue="Write a reply";
replyTxt.onfocus = function(){if(this.value==this.defaultValue) this.value='';};
replyTxt.onblur= function(){if(this.value=='') this.value=this.defaultValue;};
document.getElementById('x').appendChild(replyTxt);
}
</script>
答案 4 :(得分:-1)
实际上我正在研究一个类似的问题作为家庭作业,我发现一旦鼠标落在田地上就更好地清除田地,而不是做一个比较,如果保持不变,然后清除它。