gpt4 book ai didi

javascript - 如何更改输入值 onfocus 和 onblur(无 jquery)

转载 作者:行者123 更新时间:2023-11-29 18:25:55 25 4
gpt4 key购买 nike

我写了一些代码,有点像使用 JavaScript 的 HTML5 占位符的替代品,但它不起作用。据我所知(以我对 js 的平庸知识),一切都应该有效,但事实并非如此。请帮忙!!!这是我的代码:

JavaScript:

(function(){
var field = document.getElementById('placeholder');
var placeholdertext = "Search box"; // << change this to whatever you want the placeholder text to be

field.setAttribute("onblur", "if(value=='') { value = '" + placeholdertext + "'")
field.setAttribute("onfocus", "if(value=='" + placeholdertext + "') { value = '' }")
})();

HTML

<input type="search" value="Search box" id="placeholder">

编辑:

拜托,我不想使用 jQuery 或 inline-html-coding。感谢您的帮助,伙计们!!!

最佳答案

在您的代码中将 value 替换为 this.value(因为您需要检查触发事件的元素的值,而不是某个全局变量)并且它will work .

作为旁注,也许我更愿意在这里仍然使用 placeholder 属性,只为不支持它的浏览器提供 JS shim。这也将简化 javascript 代码部分,因为您不必使用一些变量来存储一些与 DOM 相关的数据:

field.onblur = function() {
if (this.value === '') {
this.value = this.getAttribute('placeholder');
}
};

field.onfocus = function() {
if (this.value === this.getAttribute('placeholder') ) {
this.value = '';
}
};

... 事实上,我更喜欢在这里使用 addEventListener/attachEvent 而不是 onblur/onfocus,如 this answer 中所述.

关于javascript - 如何更改输入值 onfocus 和 onblur(无 jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13224643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com