jquery:获取自定义属性的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7177512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: get value of custom attribute
提问by bflemi3
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.
html5 支持input[type=text]
元素上的占位符属性,但我需要处理不兼容的浏览器。我知道有一千个插件可用于占位符,但我想创建第 1001 个插件。
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")
.
我能够获取该input[placeholder]
元素的句柄,但尝试获取占位符属性的值返回 undefined - $("input[placeholder]").attr("placeholder")
。
I'm using jquery 1.6.2.
我正在使用 jquery 1.6.2。
Here is the jsfiddle. I modified the code to work in a browser that is html5 compatible just for testing purposes.
这是jsfiddle。我修改了代码以在与 html5 兼容的浏览器中工作,仅用于测试目的。
html
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"));
}
});
}
});
Thanks for any and all help, B
感谢您的任何帮助,B
回答by Dennis
You need some form of iteration here, as val
(except when called with a function) only works on the first element:
此处需要某种形式的迭代,因为val
(使用函数调用时除外)仅适用于第一个元素:
$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));
should be:
应该:
$("input[placeholder]").each( function () {
$(this).val( $(this).attr("placeholder") );
});
or
或者
$("input[placeholder]").val(function() {
return $(this).attr("placeholder");
});
回答by Prince Patel
You can also do this by passing function with onclick event
您也可以通过使用 onclick 事件传递函数来做到这一点
<a onclick="getColor(this);" color="red">
<script type="text/javascript">
function getColor(el)
{
color = $(el).attr('color');
alert(color);
}
</script>