这是您要做什么?请注意,我将$.on()
放在父项上,但.button
为操作选择。
.on(事件[,选择器] [,数据],handler(eventObject))
选择器一个选择器字符串,用于过滤触发事件的所选元素的后代。如果选择器为null或省略,则事件在到达选定元素时始终被触发。
http://api.jquery.com/on/
<div id="stuff">
<button class="button">Click me!</button>
<p>Stuff</p>
</div>
var $stuff = $('#stuff'),
ajaxContent = $stuff.html();
$stuff.on('click', '.button', function(){
$.get('/echo/html/', function(){
$stuff.empty();
console.log($stuff.html());
alert($stuff.html());
$stuff.html(ajaxContent);
console.log($stuff.html());
});
});
http://jsfiddle.net/62uSU/1
另一个示范:
var $stuff = $('#stuff'),
ajaxContent = $stuff.html(),
$ajaxContent,
colors = ['blue','green','red'],
color = 0;
$stuff.on('click', '.button', function(){
$.get('/echo/html/', function(){
color++;
if (color == colors.length) color = 0;
console.log($stuff.html());
alert($stuff.html());
$ajaxContent = $(ajaxContent);
$stuff.append($ajaxContent).css('color', colors[color]);
console.log($stuff.html());
});
});
http://jsfiddle.net/62uSU/2/