TypeError: $(...).live is not a function的问题解决

JerryXia 发表于 , 阅读 (18,611)


假设访问http://www.abc.com/test.html里面有段这样的代码<div class="some">1111</div>


       //完成Ajax请求,删除旧的,插入获取的新数据:<div class="some">222</div>

这时候Jquery对这个<div class="some">2222</div>的点击事件没反应了。。。。

后来在一个群里询问后发现这是因为jQuery并未对新插入的<div class="some">2222</div>绑定click事件;

jQuery API中有个live()函数,可以解决这个问题:

这个方法是基本是的 .bind() 方法的一个变体。使用 .bind() 时,选择器匹配的元素会附加一个事件处理函数,而以后再添加的元素则不会有。为此需要再使用一次 .bind() 才行。

但是接着有碰到一个问题,由于我应用的jQuery是1.9版本的,在jQuery 1.9中 .live() 不是一个函数,好像被关闭了[is closed]。下面是在stackoverflow一个问答

I have updated our jQuery and now our.live()function is not working.
Could someone assist in telling me what it's replaced by?
Read before you start doing a search and replace:
For quick/hot fixes on a live site, do not just replace the keywordlivewithon, as the parameters are different.

.live(events, function)

should map to

.on(eventType, selector, function)

The selector is very important! If you do not need to use this for any reason, set it tonull.

Migration Example 1:


$('#mainmenu a').live('click', function)

after, you move the child element (a) to the.on()selector:

$('#mainmenu').on('click', 'a', function)

Migration Example 2:


$('.myButton').live('click', function)

after, you move the element (.myButton) to the.on()selector, and find the nearest parent element (preferably with an ID):

$('#myMenu').on('click', '.myButton', function)

If you do not know what to put as the parent,bodyalways works:

$('body').on('click', '.myButton', function)
仅有 1 条评论