jQuery:获取自定义属性的值

编程入门 行业动态 更新时间:2024-10-15 18:22:46
本文介绍了jQuery:获取自定义属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

html5在input[type=text]元素上支持占位符属性,但是我需要处理不兼容的浏览器.我知道那里有一千个用于占位符的插件,但我想创建第1001个插件.

html5 supports the placeholder attribute on input[type=text] elements, but I need to handle non-compliant browsers. I know there are a thousand plugins out there for placeholder but I'd like to create the 1001st.

我能够获取input[placeholder]元素的句柄,但尝试获取占位符属性的值将返回未定义-$("input[placeholder]").attr("placeholder").

I am able to get a handle on the input[placeholder] element but trying to get the value of the placeholder attribute is returning undefined - $("input[placeholder]").attr("placeholder").

我正在使用jquery 1.6.2

I'm using jquery 1.6.2.

这是 jsfiddle .我修改了代码,使其可在html5兼容的浏览器中工作,仅用于测试目的.

Here is the jsfiddle. I modified the code to work in a browser that is html5 compatible just for testing purposes.

html

<input type="text" name="email" size="10" placeholder="EMAIL ADDRESS">

jquery

function SupportsInputPlaceholder() { var i = document.createElement("input"); return "placeholder" in i; } $(document).ready(function(){ if(!SupportsInputPlaceholder()) { //set initial value to placeholder attribute $("input[placeholder]").val($("input[placeholder]").attr("placeholder")); //create event handlers for focus and blur $("input[placeholder]").focus(function() { if($(this).val() == $(this).attr("placeholder")) { $(this).val(""); } }).blur(function() { if($(this).val() == "") { $(this).val($(this).attr("placeholder")); } }); } });

感谢所有帮助, B

推荐答案

在这里您需要某种形式的迭代,因为val(除了使用函数调用时)仅适用于第一个元素:

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

应为:

$("input[placeholder]").each( function () { $(this).val( $(this).attr("placeholder") ); });

$("input[placeholder]").val(function() { return $(this).attr("placeholder"); });

更多推荐

jQuery:获取自定义属性的值

本文发布于:2023-11-15 22:14:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   属性   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!