gpt4 book ai didi

javascript - 在没有 JQuery 的 IE 中使用 Javascript 检索 "Placeholder"值

转载 作者:行者123 更新时间:2023-12-03 16:24:54 25 4
gpt4 key购买 nike

我有一些 Javascript 代码可以检查浏览器是否支持占位符,如果不支持,它会自行创建它们。现在这适用于一些较旧的浏览器,但不是全部,尤其是 IE。

我需要做的就是获取“占位符”值,此时 IE9 中的占位符是“未定义的”。

这是我的代码:

//Test if Placeholders are supported
var test = document.createElement("input");
if ("placeholder" in test) {
var testholder = true;
}
else {
var testholder = false;
}

//Fix unsupported placeholders
function placeHolder(id)
{
var demo = document.getElementById(id);

demo.className = "fix-hint";
demo.value = demo.placeholder;

demo.onfocus = function()
{
if (this.className == "fix-hint")
{
this.value = ""; this.className = "fix-nohint";
}
};

demo.onblur = function()
{
if (this.value === "")
{
this.className = "fix-hint"; this.value = demo.placeholder;
}
};
return false;

}
我用的是0%的Jquery,感觉解决小问题太笨重了,另外想学纯Javascript。 Modernizr 也不是,尽管我可能会在某个时候开始使用它。

更新

这是工作代码。在 IE 8 和 9 中测试。(函数调用在“placeSupport”的 if/else 中。)
//Check if placeholders are supported

placeholderSupport = ("placeholder" in document.createElement("input"));
if(!placeholderSupport){
var placeSupport = false;
}else{
var placeSupport = true;}

//Support placeholders in older browsers

function placeHolder (id)
{
var el = document.getElementById(id);
var placeholder = el.getAttribute("placeholder");

el.onfocus = function ()
{
if(this.value == placeholder)
{
this.value = '';
this.className = "fix-nohint";
}
};

el.onblur = function ()
{
if(this.value.length == 0)
{
this.value = placeholder;
this.className = "fix-hint";
}
};

el.onblur();

}

最佳答案

如果您不确定是否能够使用某些功能/属性,请尝试 caniuse.com - 您会注意到占位符在 IE9 中不可用。

尝试使用 getAttribute("placeholder")

getAttribute() returns the value of the named attribute on the specified element. If the named attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details.



EXAMPLE

HTML
<input id="demo" placeholder="Rawr" />

JavaScript
var placeholder = document.getElementById("demo").getAttribute("placeholder");
console.log(placeholder);

关于javascript - 在没有 JQuery 的 IE 中使用 Javascript 检索 "Placeholder"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16199646/

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