【问题标题】:jquery: get value of custom attributejquery:获取自定义属性的值
【发布时间】:2023-03-03 10:13:01
【问题描述】:

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

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

我正在使用 jquery 1.6.2。

这里是jsfiddle。我修改了代码以在兼容 html5 的浏览器中工作,仅用于测试目的。

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"));
            }
        });
    }
});

感谢您的任何帮助, 乙

【问题讨论】:

    标签: jquery custom-attributes attr


    【解决方案1】:

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

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

    应该是:

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

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

    【讨论】:

    • $("input[placeholder]").val(function() { return $(this).attr("placeholder"); }); 会不会更好?
    • 谢谢丹尼斯。当我在每个上设置断点时,我发现它甚至没有进入函数,就像它没有找到任何与该选择器匹配的元素。但是当我把手表放在 $("input[placeholder]").val() 上时,我看到了 "",如果我给元素一个初始值,我会看到这个值。
    • @Richard 是的,这有点好。可能没有太大的差异思想。 bflemi3,您使用的是什么浏览器?您的代码适用于 Chrome 和 IE7
    • 我使用的是 firefox 5,并且我已经注释掉了检查浏览器是否支持 placeholder 属性的 if 语句,因为 firefox 5 支持 html5。
    • 我无法重现该问题。您提供的代码工作正常。你能做一个显示它的jsfiddle/jsbin吗?
    【解决方案2】:

    您也可以通过 onclick 事件传递函数来做到这一点

    <a onclick="getColor(this);" color="red">
    
    <script type="text/javascript">
    
    function getColor(el)
    {
         color = $(el).attr('color');
         alert(color);
    }
    
    </script> 
    

    【讨论】:

    • onlick...hmmm...也许应该是 onclick :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2011-03-18
    相关资源
    最近更新 更多