0

我正在尝试在 jQuery 中创建一个执行事件的函数。我的目标是创建一个功能,在页面加载或用户空白字段时将消息放入字段中。

$(function () {

  function focusField(id, message) {
    parent = $(this);

    id.color("#C8C8C8");
    id.value(message);

    parent.delegate(id, 'focus', function() {
      if( id.val() == message ) {
        id.val("");
        id.color("black");
      };
    });

    parent.delegate(id, 'keyup', function() {
      if( id.val() == "") {
        id.val(message);
        id.color("#C8C8C8");
      }
    });
  };

  $(".content").focusField($("#emaillogin"), "Email");

这不起作用,因为我认为我使用了错误的概念函数。但是有没有办法做到这一点?我的意思是如果可以创建一个函数,然后在一个元素上调用它,而不是在一个事件中调用它,而是在函数中调用事件。

普通函数使用:$element.event(function)。如果可能的话,我想将函数中的事件绑定到元素。

提前致谢!

4

1 回答 1

1

是的,您只需将您的函数附加到 jquery 原型并进行一些小改动:

$(function () {

  $.fn.focusField = function(id, message) {
    return this.each(function(){
      var parent = $(this);

      //id.color("#C8C8C8"); <--- these make no sense, what were they supposed to be doing?
      //id.value(message); <--- these make no sense, what were they supposed to be doing?

      // i don't see a reason to delegate here, just bind to focus event directly.
      parent.delegate(id, 'focus', function() {
        if( id.val() == message ) {
          id.val(""); 
          //id.color("black"); <--- these make no sense, what were they supposed to be doing?
        };
      });

      // i don't see a reason to delegate here, just bind to focus event directly.
      parent.delegate(id, 'keyup', function() {
        if( id.val() == "") {
          id.val(message); 
          //id.color("#C8C8C8"); <--- these make no sense, what were they supposed to be doing?
        }
      });
    }
  }
  $(".content").focusField($("#emaillogin"), "Email");
});
于 2013-01-21T16:24:56.910 回答