2013-05-07 22 views
0

我正在使用jQuery 2.0.0,並且我有一個包含2個鏈接的基本頁面。如果用戶點擊每個鏈接的鏈接,表單通過Ajax加載並注入容器。早些時候可以通過live()將事件綁定到將來的元素,但是現在應該可以用on()我想,但它不會觸發submit事件,就好像在注入表單後注入腳本一樣。作爲瀏覽器,我使用的是Firefox 20jQuery不會在注入後的表單上觸發事件

頁:

<!-- Normal HTML5 head with jQuery loader //--> 
<a href="./login">Login</a> 
<!-- Normal HTML5 end //--> 

登錄(通過Ajax):

<form id="login" action="./login"> 
    <label for="username">Username:</label> 
    <input type="text" name="username" id="username" /> 

    <label for="password">Password:</label> 
    <input type="password" name="password" id="password" /> 

    <input type="submit" value="Login" /> 
</form> 

最後我的腳本:

$(document).ready(function() { 

    $('a').on('click', function(e) { 
     $('body').load($(this).attr('href')); 
     e.preventDefault(); 
    }); 


    $('#login').on('submit', function(e) { 
     e.preventDefault(); 

     // Some validation and as test if event is fired 
     alert("Fired!"); 
    }); 

}); 
+0

[使用jQuery on()連接點擊事件不可能通過Ajax調用觸發注入的HTML](http://stackoverflow.com/questions/8756684/wiring-up-click-event -using-jquery-on-doesnt-fire-on-injected-html-via-ajax-c) – undefined 2013-05-07 22:46:39

+1

'-1'這個問題沒有顯示任何研究工作。 – undefined 2013-05-07 22:47:27

+0

我現在正在使用jQuery 2.0,並且沒有'live()'方法了。所以你發佈的話題的答案似乎已經過時了。 – David 2013-05-07 22:58:36

回答

0

opened a bug on jQuery和似乎每個人都必須使用像this example on jsFiddle這樣的活動代表團:

$('#inject').on('click', function(e) { 
    $('body').html('<form id="login" action="./login"> \ 
         <label for="username">Username:</label> \ 
         <input type="text" name="username" id="username" /> \ 
         <label for="password">Password:</label> \ 
         <input type="password" name="password" id="password" /> \ 
         <input type="submit" value="Login" /> \ 
        </form>'); 
}); 

$('body').on('submit', '#login', function(e) { 
    e.preventDefault(); 

    // Some validation and as test if event is fired 
    alert("Fired!"); 
}); 
相關問題