javascript - Need click to trigger after appending element -
please see below code:
html:
<p>click paragraph.</p>
js:
$("p").live("click", function(){ alert("the paragraph clicked."); $("body").append("<p>this newly added. has click</p>") });
now element appending correctly. click not triggering appended element. if using live
instead of on
working fine. live depreciated. do.
use delegate style .on
.on( events [, selector ] [, data ], handler )
- events type: string 1 or more space-separated event types , optional namespaces, such "click" or "keydown.myplugin".
- selector type: string selector string filter descendants of selected elements trigger event. if selector null or omitted, event triggered when reaches selected element.
- data type: data passed handler in event.data when event triggered.
- handler type: function( event eventobject [, extraparameter ] [, ... ] ) function execute when event triggered. value false allowed shorthand function return false.
as don't want pass data, can write in form:
$(body).on('click', 'p', handler)
which omits data param.
$("body").on("click", "p", function(){ alert("the paragraph clicked."); $("body").append("<p>this newly added. has click</p>") });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <p>click paragraph.</p>
Comments
Post a Comment