Home > Article > Web Front-end > What to do if jquery click event fails
The jquery click event fails because live is no longer recommended after JQUERY1.7. The solution is to change the code to "$("#a").on('click',function() {for(var i=0 ; i< leng;i ){...}}" can be done.
## Recommended: "jquery video tutorial"
Put the complete code first
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script> <style type="text/css"> #a{ width:50px; height:50px; background: rgb(54, 54, 54); } #b{ width:50px; height:50px; background: rgb(144, 243, 182); } #d{ width:50px; height:50px; background: rgb(114, 116, 231); } li{ list-style: none; } .display{display:block;} .hide{display:none;} </style> </head> <body> <p id="a"></p> <p id="b"></p> <p id="d"></p> <p id="c"> <ul> <li id="c1">11111111</li> <li id="c2">22222222</li> <li id="c3">33333333</li> </ul> </p> <script type="text/javascript"> var link = $('ul li'); var leng = c.querySelectorAll("li").length; $("#a").on('click',function(){ for(var i=0 ; i< leng;i++){ link[i].className = 'display' } }) $("#b").on('click',function(){ for(var i=0 ; i< leng;i++){ if(link[i].id !== 'c2'){ link[i].className = 'hide' }else{ link[i].className = 'display' } } }) $("#d").on('click',function(){ for(var i=0 ; i< leng;i++){ if(link[i].id !== 'c1'){ link[i].className = 'hide' }else{ link[i].className = 'display' } } }) </script> </body> </html>
At first the click event was written like this, but it was found that the click was invalid. The ones that support binding events to dynamic elements and attributes are live and on, among which live is not recommended after JQUERY 1.7. Now we mainly use on. When using on, we should also pay attention to it. The elements before on must also exist in the dom when the page is loaded. Dynamic elements or styles can be placed in the second parameter of on.
$('#a').click = function(){ for(var i=0 ; i< leng;i++){ link[i].className = 'display' } }
Later, just change the code to the following code
$("#a").on('click',function(){ for(var i=0 ; i< leng;i++){ link[i].className = 'display' } })
The above is the detailed content of What to do if jquery click event fails. For more information, please follow other related articles on the PHP Chinese website!