从.live更改为.on

L84*_*L84 2 javascript jquery jquery-on

我知道.live是折旧的,最近我正在更新页面并意识到我正在使用.live我想切换到.on但不明白要改变什么.这是我目前的代码:

    //Script for Choosing which form to display
$("#email-button, #text-button").live('click',
function(){  

    //figure out what button was clicked. 
    if(this.id === "email-button"){
        var btnA = $(this);
        var btnB = $("#text-button");
        var divA = $('#email-form');
        var divB = $('#text-form');
    }
    else{
        btnA = $(this);
        btnB = $("#email-button");
        divA = $('#text-form');
        divB = $('#email-form');
    }

    //make sure it is not already active, no use to show/hide when it is already set
    if(btnA.hasClass('dark_button_span')){
        return; 
    }

    //see if div is visible, if so hide, than show first div
    if(divB.is(":visible")){        
        divB.fadeOut("slow", function(){
             divA.fadeIn("slow");
        });
    }
    else{//if already hidden, just show the first div
        divA.fadeIn("slow");            
    }

    //Add and remove classes to the buttons to switch state
    btnA.addClass('dark_button_span').removeClass('light_button_span');
    btnB.removeClass('dark_button_span').addClass('light_button_span');
  }    
);
Run Code Online (Sandbox Code Playgroud)

我帮助编写上面的脚本,不知道要改变什么.简单地将.live更改为.on不起作用.

任何帮助将不胜感激!

谢谢!

Jan*_*Jan 5

on的语法是

$("containerElement").on("click", "targetElement(s)", function(){ });
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下它可能是

$("body").on("click", "#email-button, #text-button", function(){ });
Run Code Online (Sandbox Code Playgroud)

但更具体而不是body一个好主意.