如何使用jquery动态更新元素的类?

时间:2016-06-01 12:04:21

标签: jquery html

     <div class="form-group">            
        <button type="submit"id="form_submit">
           <span class="glyphicon glyphicon-user"></span> Sign Up
        </button>            
        <a style="cursor:pointer;" class="click_login">Already signed up! Then  Login</a>
     </div>

jquery的:

$(document).ready(function(){
    // form click login
    $(".click_login").on("click",function(){

        $(this).html("New Member! Then Sign Up");
        $(this).removeClass('click_login').addClass('click_signup');
        alert($(this).attr("class"));
        $("#form_submit").html('<span class="glyphicon glyphicon-log-in"></span> Login');         
    });

    // form click signup
    $(".click_signup").on("click",function(){

        $(this).html("Already signed up! Then  Login");
        $(this).removeClass('click_signup').addClass('click_login');
        $("#form_submit").html('<span class="glyphicon glyphicon-user"></span> signup');         
    });
   });

当我点击链接时,它会变为“登录”按钮。但是一旦通过jquery更新,当我再次点击链接时,它不会更改为新类以获得注册按钮。新类通过jquery更新,但on click函数不会触发相同元素的新类选择器。

2 个答案:

答案 0 :(得分:2)

USe $(document).on(&#34;点击&#34;)事件动态添加内容:

    $(document).on("click",".click_login",function(){
        $(this).html("New Member! Then Sign Up");
        $(this).removeClass('click_login').addClass('click_signup');
        alert($(this).attr("class"));
        $("#form_submit").html('<span class="glyphicon glyphicon-log-in"></span> Login');         
    });

    // form click signup
    $(document).on("click",".click_signup",function(){

        $(this).html("Already signed up! Then  Login");
        $(this).removeClass('click_signup').addClass('click_login');
        $("#form_submit").html('<span class="glyphicon glyphicon-user"></span> signup');         
    });

答案 1 :(得分:1)

尝试

 // form click signup
    $(document).on("click",".click_signup",function(){

        $(this).html("Already signed up! Then  Login");
        $(this).removeClass('click_signup').addClass('click_login');
        $("#form_submit").html('<span class="glyphicon glyphicon-user"></span> signup');         
    });