大家好,我在这里有点困惑。我正在使用replaceWith();
jQuery 替换一个元素,效果很好。但是在转换之后,可点击元素不再起作用。这是我的代码
问问题
365 次
2 回答
2
那是因为替换元素时事件绑定丢失。replaceWith()
本质上删除元素及其所有事件绑定,然后用新元素替换它。它不会持久化事件绑定。
而是使用绑定点击事件.on()
。
$('.menu').on('click', 'a', function() {
...
});
更新小提琴:http: //jsfiddle.net/RTPhR/1/
于 2013-08-13T17:14:49.520 回答
0
http://jsfiddle.net/RTPhR/5/ 将事件绑定到菜单而不是链接。
$(document).ready(function() {
$('.menu').on('click','a',function() {
var $this = $(this),
element = $this.attr('name');
if (element == 'opt1') {
alert('opcion 1');
} else if (element == 'opt2') {
alert('opcion 2');
$this.replaceWith("<a href='#' name='cerrar'>VOLVER</a>");
} else if (element == 'cerrar') {
alert('close!');
}
});
});
于 2013-08-13T17:27:46.027 回答