javascript 当字段为空时,val() 返回占位符值而不是 IE8,9 中的实际值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11208417/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:24:18  来源:igfitidea点击:

val() returns Placeholder value instead of the actual value in IE8,9 when the field is empty

javascriptjquery

提问by user1184100

Placeholder attribute shown below works fine in firefox but if val() is called when the field is emptyit returns the placeholder value instead of the actual value in the text.

下面显示的占位符属性在 Firefox 中工作正常,但如果在字段为时调用 val()它将返回占位符值而不是文本中的实际值。

JSFiddle - http://jsfiddle.net/Jrfwr/2/

JSFiddle - http://jsfiddle.net/Jrfwr/2/

<input id="tlt" type="text" placeholder="Enter Title" />

JSCode

代码

function placeHolderFallBack() {
   if ("placeholder" in document.createElement("input")) {
       return;
   }
   else {
       $('[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();
       $('[placeholder]').parents('form').submit(function () {
           $(this).find('[placeholder]').each(function () {
               var input = $(this);
               if (input.val() == input.attr('placeholder')) {
                   input.val('');
               }
           })
       });
   }
}

采纳答案by Thomas

You could override the val() method but I don't like doing that :D

您可以覆盖 val() 方法,但我不喜欢这样做 :D

I wrote a simple pVal()function which does the job

我写了一个简单的pVal()函数来完成这项工作

$.fn.pVal = function(){
    var $this = $(this),
        val = $this.eq(0).val();
    if(val == $this.attr('placeholder'))
        return '';
    else
        return val;
}
$(function(){
    alert($('input').val())
    alert($('input').pVal())
});?

http://jsfiddle.net/W7JKt/3/

http://jsfiddle.net/W7JKt/3/

回答by Daniel

In your JSFiddle code you get the value of the textbox in a BUTTON CLICK event... and your code that checks if the current value of the textbox is equal to the placeholder executes in the FORM SUBMIT event.

在您的 JSFiddle 代码中,您在 BUTTON CLICK 事件中获得文本框的值......并且您的代码检查文本框的当前值是否等于在 FORM SUBMIT 事件中执行的占位符。

So... the problem is that the BUTTON's CLICK event executes before the FORM's SUBMIT event.

所以...问题是BUTTON的CLICK事件在FORM的SUBMIT事件之前执行。

This code shows an example of how to get the correct value

此代码显示了如何获取正确值的示例

Hope that helps.

希望有帮助。

回答by haroonxml