2011-03-06 29 views
0
$(document).ready(function() { 
    $('.watermark').focus(function() { 
     if (this.className == 'watermark') 
     { 
      this.className = ''; 
      this.value = ''; 
     } 
    }); 

    $('.watermark').blur(function() { 
     if (this.value == '') 
     { 
      this.className = 'watermark'; 
      this.value = 'Type here'; 
     } 
    }); 
}); 

我有這個代碼塊,除了它不是動態的,它可以完美地工作。我想知道是否有一種優雅的方式來動態地將值重置爲原始值。我在想,也許如果你定義了原始文本的ID或其他類型的屬性,你可以重置它,或者你可以使用變量或數組或元組。 SO認爲做這件事的最好方法是什麼?如何重構此代碼塊以簡化和動態?

+2

我重構通常延伸我[代碼傳遞給谷歌(http://www.google.com/search? q = jquery + watermark + plugin&ie = utf-8&oe = utf-8&aq = t&rls = org.mozilla:en-US:official&client = firefox-a)and [see if if](http://plugins.jquery.com/project/ updnWatermark)我[已重新發明](http://plugins.jquery.com/project/TinyWatermark)[wheel](http://code.google.com/p/jquery-watermark/)。 – 2011-03-06 21:05:21

回答

1

如何將值存儲到輸入的其他屬性?

$(document).ready(function() { 
    $('.watermark').focus(function() { 
     if (this.className == 'watermark') 
     { 
      this.className = ''; 
      this.title = this.value; 
      this.value = ''; 
     } 
    }); 

    $('.watermark').blur(function() { 
     if (this.value == '') 
     { 
      this.className = 'watermark'; 
      this.value = this.title; 
     } 
    }); 
}); 
+0

是的,非常感謝!^_ ^ – 2011-03-06 21:05:26

0

在這種情況下我更喜歡使用JavaScript回落使用HTML5(placeholder attrinute)。

function supports_input_placeholder() { 
    var i = document.createElement('input'); 
    return 'placeholder' in i; 
} 
$(document).ready(function() { 
    if (!supports_input_placeholder()) 
    { 
    $('input').each(function(){ 
     $(this).val($(this).attr('placeholder')) 
    }); 
    $('input').focus(function() { 
     if (this.className == 'watermark') 
     { 
      this.className = ''; 
      this.value = ''; 
     } 
    }); 

    $('input').blur(function() { 
     if (this.value == '') 
     { 
      this.className = 'watermark'; 
      this.value = $(this).attr('placeholder'); 
     } 
    }); 
    } 

}); 

此腳本將檢測原始佔位符是否可用,如果不是,則它將從佔位符屬性中獲取文本並進行模擬。

0

你只需將它存儲在一個變量,如果它的範圍的每一個元素:

$(function() { 
    $('.watermark').each(function() { 
    var lead = $(this).val(); 
    $(this).focus(function() { 
     if ($(this).val() == lead) $(this).val(''); 
    }).blur(function() { 
     if ($(this).val() == '') $(this).val(lead); 
    }); 
    }); 
});