jquery 1.7+,body追加了一个新元素,以及如何使用on()而不是live()将action绑定到它



我在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/

  • 首先单击button,然后尝试单击trigger
  • 然后,单击红色的on click me消息

在div change\上引发jQuery事件

对于IEjQuery监视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:' + 'nn' + this.innerHTML);
} else {
// alert('Content removed! Current content:' + 'nn' + this.innerHTML);
};
});
$('#trgbutton').click(function() {
$('.future').trigger('change');
});
function myhandler(event) {
alert(event.data.name);
}​

我很确定这段代码是罪魁祸首。

$(this).on('click', {
name : 'liujun'
}, myhandler);

它看起来不是一个有效的语法。

如果你想传递一个参数,试试这个

$(this).on("click", function(e) {
myHandler({name: liujun})
})

事实上,这非常令人困惑,如果你能在jsFiddle中向我们展示HTML,也许我们可以提供更多帮助。

最新更新