jquery has a handy delegate (event delegation) feature that allows you to bind an event handler to current and future (dynamically added) elements.
For example, after dynamically adding an input text box, I want all text boxes (whether or not dynamically added) to automatically capitalize when the focus is obtained.
Copy Code code as follows:
<!doctype html>
<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>
<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>
Next, I want to add some small features, when the focus, but also to make the text box automatically select all.
Copy Code code as follows:
$ (). Ready (function () {
$ ("#ulTarget"). Delegate (": Text", "Focus", function () {
$ (this). Val ($ (this). Val (). toUpperCase ()). Select ();
});
})
But actually measured down,. Select () Anyway is not working, but please out settimeout
Copy Code code as follows:
$ (). Ready (function () {
$ ("#ulTarget"). Delegate (": Text", "Focus", function () {
var jqobj = $ (this);
Jqobj.val (Jqobj.val (). toUpperCase ());
settimeout (function () {jqobj.select ();},100);
});
})
solved.