confusion over simple variable declaration jQuery “$variable” vs javascript “var”

后端 未结 5 1968
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 15:48

I have this simple ghost text implementation:

HTML code:

5条回答
  •  甜味超标
    2020-12-04 16:13

    In to addition @mgiuca's answer here is a little more elaborate approach to your problem that also shows some of the jQuery concep:

    $(document).ready(function () { 
      // define two helper functions
      var removeDefault = function () {
        if( $(this).val() == $(this).data("defaultValue") ) {
          $(this).val("").removeClass("ghText");
        }
      };
      var setDefault = function () {
        if( $(this).val() == "" ) {
          $(this).val( $(this).data("defaultValue") ).addClass("ghText");
        }
      };
      // the following works on all input elements
      $("#searchPanel form input.ghText").each(function () {
        $(this)
        .data("defaultValue", $(this).val())
        .focus(removeDefault)
        .blur(setDefault);
      });
    }); 
    

    Note

    • the use of .data() to associate a value with a specific element.
    • the use of .each() to apply the same behavior to any number of elements
    • the use function references for .focus() and .blur() - jQuery will always set the this correctly on its own
    • see it working over here http://jsfiddle.net/xsXxn/

提交回复
热议问题