jQuery的.val()为Firefox和Chrome

时间:2016-01-28 04:43:57

标签: javascript jquery html google-chrome firefox

鉴于以下HTML,我在使用最新的jQuery时会看到在Firefox和Chrome中返回不同的值:

HTML:

<input type="text" name="name" id="name" placeholder="Type Here">
<input type="email" name="email" id="email" placeholder="Type Here">

jQuery的:

jQuery("#name").val();  // Returns "Type Here" in Chrome, blank in Firefox
jQuery("#email").val(); // Returns "Type Here" in Chrome, blank in Firefox

在我看来,上面应该返回一个空白字符串,因为“在这里输入”只是占位符文本。

为何与众不同?

1 个答案:

答案 0 :(得分:1)

正如@BarMar评论的那样,我发现了一些丑陋的旧代码,它采用了占位符属性并使其成为实际值:

/* Placeholder Fix */
$('[placeholder]').focus(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
    }
}).blur(function() {
    var input = $(this);
    if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }
}).blur().parents('form').submit(function() {
    $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
        }
    })
});

删除了这个,现在很好。感谢。

相关问题