我在jquery 1.6之前使用了live函数。 在jquery 1.7+中,不推荐使用live函数,而是使用on函数。 我有一个问题,请使用以下代码:
$('#button').on('click', function(event) {
//add a new element to body
$('body').append('<div class="future">I am a new div</div>');
});
//bind a action to new element which is add a moment ago.
$('body').on('change', '.future', function() {
$(this).css({
'color' : 'red',
'font-weight' : 'bold'
});
$(this).text("on click me.");
$(this).on('click', {
name : 'liujun'
}, myhandler);
});
function myhandler(event) {
alert(event.data.name);
}
新操作不起作用,语法正确。为什么?
最佳答案
工作演示 http://jsfiddle.net/nQDs2/4/
- 首先单击
按钮
,然后尝试单击触发
- 然后,点击红色的
点击我
消息。
Fire jQuery event on div change\
对于IE jQuery watch div
我不确定为什么我会被否决,希望它适合您的原因:)
代码
$('#button').on('click', function(event) {
//add a new element to body
$('body').append('<div class="future">I am a new div</div>');
});
//bind a action to new element which is add a moment ago.
$('body').on('change', '.future', function() {
$(this).css({
'color': 'red',
'font-weight': 'bold'
});
$(this).text("on click me.");
$(this).on('click', {
name: 'liujun'
}, myhandler);
}).bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
// alert('Content added! Current content:' + '\n\n' + this.innerHTML);
} else {
// alert('Content removed! Current content:' + '\n\n' + this.innerHTML);
};
});
$('#trgbutton').click(function() {
$('.future').trigger('change');
});
function myhandler(event) {
alert(event.data.name);
}
关于jquery 1.7+,body 追加一个新元素,以及如何使用 on() 而不是 live() 将操作绑定(bind)到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12880172/