1

IE 不支持输入元素的占位符。我正在尝试使用 jquery 解决方法

我想要的是在页面加载字段值 sld 得到初始化。我能够专注于现场。例如。这行得通

  // ThiS Works on focus, "Email" is shown in text box
$(function() {
  $("#login_email").focus(function()
  {
      if ($(this).val() == "")
      {
          $(this).val("Email");
      }
  });
});

  // I hoped that this will intialize on page load. But this does not work ???
  // This does not work

$(function() {
  $("#login_email").val("Email");
});

我怎样才能解决这个问题?

为什么选项 2 不起作用但选项 1 起作用?有什么区别??

4

3 回答 3

0

我最终这样做了:

  $("#login_email, #login_password").blur(function() {
    var input = $(this);
    if (input.val() == '') {
      input.addClass("placeholder");
      input.val(input.attr("placeholder"));
    }
  })
  // This is needed at the time of page load. There is
  // potential race condition happening here.
  setTimeout(function() {
    $("#login_email, #login_password").each(function() {
      var input = $(this);
      if (input.val() == '') {
        input.addClass("placeholder");
        input.val(input.attr("placeholder"));
      }
    })
  }, 50);
于 2013-08-06T20:50:18.147 回答
0

我可以建议这种方法吗

Javascript

$(function() {
    $("#login_email").val($("#login_email").attr("placeholder"));

    $("#login_email").on("focus", function() {
      var elem = $(this);
      if (elem.val() == "") {
          elem.val(elem.attr("placeholder"));
      } else if(elem.val() == elem.attr("placeholder")) {
          elem.val("");
      }
    });

    $("#login_email").on("blur", function() {
      var elem = $(this);
      if (elem.val() == "") {
          elem.val(elem.attr("placeholder"));
      }
    });
});

html

<input type="text" id="login_email" placeholder="Email">

这样,它的可重用性更高。
有关更多详细信息,请参见 JsFiddle:http: //jsfiddle.net/SUdbs/

于 2013-08-06T20:14:27.550 回答
0
$(".#login_email").val("Email")
    .focus(function(){
        if($(this).val() == "Email"){
            $(this).val("");
        }
    })
    .blur(function(){
        if($(this).val().length == 0){
            $(this).val("Email");
        }
    });

这将为您提供类似占位符的输入。我喜欢占位符如何在焦点上消失而不是消失,但是为了减少代码膨胀,这可能对你有好处。

于 2013-08-06T20:14:56.120 回答