JQuery has a very useful delegate function, which can bind an event handler function to the current and future (dynamically added) elements.
For example, in the following example, after dynamically adding an input text box, I want all text boxes (whether or not they are dynamically added) to be automatically converted to uppercase when getting the focus.
Copy codeThe Code is as follows:
<! Doctype html>
<Html>
<Head>
<Title> delegate test </title>
<Script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.js"> </script>
<Style type = "text/css">
* {Padding: 0; margin: 0; list-style: none; margin: 5px}
</Style>
<Script type = "text/javascript">
// Dynamically add a line of text input box
Function addInput (){
$ ("# UlTarget"). append ("<li> <input type = \" text \ "value = \" aaaaaa \ "/> </li> ");
}
$ (). Ready (function (){
$ ("# UlTarget"). delegate (": text", "focus", function (){
$ (This). val ($ (this). val (). toUpperCase ());
});
})
</Script>
</Head>
<Body>
<Ul id = "ulTarget">
<Li> <input type = "text" value = "123456abc"/> </li>
<Li> <input type = "text" value = "123456abc"/> </li>
<Li> <input type = "text" value = "123456abc"/> </li>
<Li> <input type = "text" value = "123456abc"/> </li>
</Ul>
<Button id = "btnAdd" onclick = "addInput ()"> add input </button>
</Body>
</Html>
Next, I want to add some small functions. When getting the focus, I also want the text box to be automatically selected.
Copy codeThe Code is as follows:
$ (). Ready (function (){
$ ("# UlTarget"). delegate (": text", "focus", function (){
$ (This). val ($ (this). val (). toUpperCase (). select ();
});
})
However, in actual tests,. select () does not work.
Copy codeThe Code is as follows:
$ (). Ready (function (){
$ ("# UlTarget"). delegate (": text", "focus", function (){
Var jqObj = $ (this );
JqObj. val (jqObj. val (). toUpperCase ());
SetTimeout (function () {jqObj. select () ;},100 );
});
})
Solved.