2016-11-07 22 views
1

好了,我的問題說明如下:如何通過jquery .html創建href,然後使用它的事件?

我有這樣的javascript代碼,以創建A HREF在表:

$('#table').html('<a name="example" class="one">One</a><a name="example" class="two">Two</a>'); 

然後,我想知道這a標籤我按下....是這樣的:

$("a[name=example]").click(function(e) { 
    var example= $(this).attr("class"); 
    alert(example); 
} 

但是,這並不工作...

你能幫助我嗎?

Thx 4 advance!

+0

閱讀有關[__'Event delegation'__](https://learn.jquery.com/events/event-delegation/) – Rayon

回答

1

你應該使用事件代表團on()到Click事件附加到新的DOM(a標籤)動態添加到頁面的腳本:

$("#table").on('click','a[name=example]',function(e) { 
    var example= $(this).attr("class"); 
    alert(example); 
}) 

希望這有助於。

$('#table').html('<a name="example" class="one">One</a><br><a name="example" class="two">Two</a>'); 
 

 
$("#table").on('click','a[name=example]',function(e) { 
 
    var example= $(this).attr("class"); 
 
    alert(example); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="table">

0

這是你應該怎麼做。

$("#table").on('click','a[name="example"]',function() { 
 
    var example= $(this).attr("class"); 
 
    alert(example); 
 
}); 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!DOCTYPE> 
 
<html> 
 
    <body> 
 
    <div id="table"> 
 
    <a name="example" class="one">One</a> 
 
    <a name="example" class="two">Two</a> 
 
    </div> 
 
    </body> 
 
    
 
    
 
</html>

相關問題