我希望每次初始化 Dom 元素时都会触发一个事件,如下所示:
HTML
<div id="container">
<div id="data">data!</div>
</div>
<div id="clickme">Click me!</div>
Javascript
$(function() {
var i = 0;
$('#clickme').click(function() {
$('#container').html('<div id="data">data '+i+'</div>');
i++;
});
// this event gets called only the first time #data element is ready
// I want it to be called each time #data comes into being
$('#data').ready(function() {
alert('element data ready!');
});
});
我试过了:
// doesn't work
$('#data').live('ready', function() {
alert('element data ready (live)');
});
编辑:我有兴趣为 ajax 插入的元素执行此操作。例如:
$.post('/myaction/', {
param: 'value'
},
function(data) {
$('#someContainer').replaceWith(data);
});
// this function operates on elements returned by the ajax call, so they are not available at this point.
myFunction();
// so I'd better call myFunction() when the ajax data is inserted
});
在这里摆弄:http: //jsfiddle.net/nf8CP/