When you click the mouse, hide or show the P element:
$ ("div"). Delegate ("button", "click", Function () { $ ("P"). Slidetoggle ();});
The delegate () method adds one or more event handlers for the specified element (the child element of the selected element) and specifies the function to run when these events occur.
Event handlers that use the delegate () method apply to current or future elements, such as new elements created by a script.
Add an event handler to a future element
How to use the delegate () method to add an event handler to an element that has not yet been created.
<script type= "Text/javascript" src= "/jquery/jquery.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (function () {
$ ("div"). Delegate ("P", "click", Function () {
$ (this). Slidetoggle ();
});
$ ("button"). Click (function () {
$ ("<p> This is a new paragraph. </p> "). InsertAfter (" button ");
});
});
</script>
<body>
<div style= "Background-color:yellow" >
<p> this is a paragraph. </p>
<p> Click any of the P elements and it will disappear. Include this paragraph. </p>
<button> Insert a new P element after this button </button>
</div>
<p><b> note:</b> by using the delegate () method instead of live (), only the P element in the DIV element is affected. </p>
</body>
When you click the button, hide or show the P element:
$ ("button"). Live ("Click", Function () { $ ("P"). Slidetoggle ();});
Definition and usage
The live () method attaches one or more event handlers to the selected element, and specifies the function to run when these events occur.
The event handlers attached through the live () method apply to the current and future elements of the matching selector (such as new elements created by the script).
Grammar
$ (selector). Live (event,data,function)
Parameters |
Description |
Event |
Necessary. Specifies one or more events that are attached to an element. Multiple events are separated by a space. Must be a valid event. |
Data |
Optional. Specifies additional data that is passed to the function. |
function |
Necessary. Specifies the function to run when an event occurs. |
Add an event handler to a future element
How to use the Live () method to add an event handler to an element that has not yet been created.
<script type= "Text/javascript" src= "/jquery/jquery.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (function () {
$ ("P"). Live ("Click", Function () {
$ (this). Slidetoggle ();
});
$ ("button"). Click (function () {
$ ("<p>this is a new paragraph.</p>"). InsertAfter ("button");
});
});
</script>
<body>
<p> this is a paragraph. </p>
<p> Clicking on any P element will make it disappear. Include this paragraph. </p>
<button> Insert a new P element after this button </button>
<p><b> Note:</b> The new P element will also disappear when clicked by using the Live () method instead of the bind () method. </p>
</body>