You can avoid storing data in the DOM using the data method, and some front-end development ER likes to use HTML attributes to store data;
Using the "alt" attribute to store data as a parameter name is actually not semantic for HTML.
We can use the jquery data method to store data for an element in the page:
HTML section:
1 <formID= "Testform">2 <inputtype= "text"class= "Clear"value= "Always cleared" />3 <inputtype= "text"class= "Clear Once"value= "Cleared only once" />4 <inputtype= "text"value= "Normal text" />5 </form>
JS section:
1$(function() {2 //Remove the input field with the clear class3 //(Note: "Clear once" is a two class clear and once)4$ (' #testform input.clear '). each (function(){5 //storing data by using data method6$( This). Data ("TXT", $.trim ($ ( This). Val ()));//This is the this element of the following focus event7}). Focus (function(){8 //determines whether the value in the field is the same as the default value when the focus is obtained, and empties if the same9 if($.trim ($ ( This). val ()) = = = $ ( This). Data ("TXT") ) {Ten$( This). Val (""); One } A}). blur (function(){ - //add blur time to the domain with class clear to restore the default value - //but if class is once then ignore the if($.trim ($ ( This). val ()) = = = "" &&!$ ( This). Hasclass ("Once") ) { - //Restore saved Data -$( This). Val ($ ( This). Data ("TXT") ); - } + }); -});
Attention:
1.js section, the 4th line of code, we use each to traverse all selector elements (sometimes not only one element requires this effect)
2.js section, the 6th line of code, the removal of the space before and after the Val value ($.trim method) into data (' tet '). Here this represents the this in all the elements traversed by each
Use the jquery data method to store data for an element in the page (get focus, clear default value)