jquery不起作用,但使用1.7.1库 [英] jquery on does not work but live does using 1.7.1 library

查看:153
本文介绍了jquery不起作用,但使用1.7.1库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态创建的按钮,所以我需要在我的代码上使用.live。这是一个例子:

  $('#send')。live('click',function(){
.....
.....代码.....
.....
});

我正在使用jQuery库1.7.1,我想将其改为使用.on,但是不行为什么是这样?语法是否不同?



我查看了文档,我似乎没有做错什么。我不介意把它像现场,但是我想知道我是否在做错事。



http://api.jquery.com/on/

解决方案

语法是否不同?是。您是否阅读了您链接到的所有 .on() doco页面?



以下有关如何从 .live()切换到 .delegate() .on()来自 .live() doco页面

  $(selector).live(events,data,handler); // jQuery 1.3+ 
$(document).delegate(selector,events,data,handler); // jQuery 1.4.3+
$(document).on(events,selector,data,handler); // jQuery 1.7+

所以在你想要的情况下:

  $(document).on('click','#send',function(){
//你的代码在这里
}) ;注意,尽管最好不要使用 $(document) / code>,您将使用 $(someotherelement)将处理程序附加到靠近#send元素的元素。如果可以,使用'#send'的直接父元素的任何一个,或者如果父代也动态创建,则使用父代。


i have a button that is created dynamically so i need to use .live on my code. Here's an example:

$('#send').live('click', function(){
.....
..... code .....
.....
});

I'm using jQuery library 1.7.1 and i wanted to change it to using .on but it does not work. Why is this? Is the syntax different?

I looked at the documentation and I dont seem to be doing anything wrong. I dont mind leaving it like live but i would like to know if I'm doing something wrong.

http://api.jquery.com/on/

解决方案

Is the syntax different? Yes. Did you read all of the .on() doco page you linked to?

The following summary about how to switch from .live() to .delegate() or .on() is from the .live() doco page:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

So in your case you want:

$(document).on('click', '#send', function(){
   // your code here
});

Note though that ideally you won't be using $(document), you'll be using $(someotherelement) to attach the handler to an element closer to your '#send' element. If you can, use whatever the direct parent element of '#send' is, or if the parent is dynamically created too use its parent.

这篇关于jquery不起作用,但使用1.7.1库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆