Reputation: 6894
I have a script where in i want to use live in below code.
if($('#Menu').length >0) {
$('#Menu >li').click(function() {
});
}
How can i use it ?
Upvotes: 0
Views: 163
Reputation: 60516
Use on instead of live
as it's deprecated as of 1.7
if($('#Menu').length) {
$('#Menu').on('click', '> li', function() {
});
}
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
In case you are using jQuery version < 1.7
and >= 1.4.2
, you can use delegate
$('#Menu').delegate('> li', 'click', function() { // different argument order than on
});
Upvotes: 5
Reputation: 137350
You don't.
.live()
was deprecated in favor of .delegate()
, then .delegate()
(and .bind()
etc.) was deprecated in favor of .on()
.
.live()
's successorThis could give you similar result:
$('#Menu').on('click', '> li', function(){
});
.on()
, use .delegate()
As I mentioned, .live()
was deprecated in favor of .delegate()
, so if you do not have .on()
available in your version of jQuery, you should try to use .delegate()
first:
$('#Menu').delegate('> li', 'click', function(){
});
live()
example doing something similarIf you insist on .live()
, you can write code like that:
$('#Menu > li').live('click', function(){
});
In general you do not need to check if something exists to add a event handler to it. jQuery will search for the element and if not found, it will just not add event handler, so you can write:
$('#Menu >li').click(function() {
});
instead of what you have written in your question.
Upvotes: 2
Reputation: 1917
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
In your case you can use like this
if($('#Menu').length >0) {
$('#Menu >li').live("click", function() {
});
}
Upvotes: 1
Reputation: 10619
I think something like below:
if($('#Menu').length >0) {
$('#Menu >li').live('click', function() {
});
}
Upvotes: 1
Reputation: 148524
you should not use live
.
you should use on
the Live is deprecated - and should not be used. p.s. this also replace the delegate syntax - if you wish...
you dont have to supply the second param - then it will listen to the container itself and all its childs +subchilds. since (1.7+)
example :
$(".myDiv").on("click","#myButton",function (){
alert('1');
})
Upvotes: 1
Reputation: 2265
.live( events, handler(eventObject) )
<script>
$("#Menu >li").live("click", function(){
});
</script>
Upvotes: 1