2

I have some dynamically generated content that contains some links on an ajax call success. The links are generated like this.

$('#mySomething').append('<a href = "' + url + '" target = "_blank" class = "myclickclass">' + Name + '</a>');

I tried

$('a.myclickclass').click(), 
$('.myclickclass').click(), 
$('.myclickclass').on('click', 'a', function({})), 

and even

$(document).on('click', '.myclickclass a', function (e) {} );

But nothing seems to happen. The new tab is opened, but the event is ignored.

Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
icebp
  • 1,608
  • 1
  • 14
  • 24

3 Answers3

3

Use $(".myclickclass")[0].click()

You can directly attach an event to this new anchor.

$('body').append($('<a href = "http://www.google.de" class = "myclickclass">Test</a>')
        .click(function() {
            alert("Hey there");
        }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>

The message is printed.

konqi
  • 5,137
  • 3
  • 34
  • 52
l1e3e3t7
  • 124
  • 11
1

delegated event must work

$(document).on('click', '.myclickclass', function (e) {

alert("yes")

} );
Amar Singh
  • 5,464
  • 2
  • 26
  • 55
0

var url = 'http://www.google.com';
var Name = "Link";
$('#mySomething').append('<a href = "' + url + '" target = "_blank" class = "myclickclass">' + Name + '</a>');

$('a.myclickclass').on('click',function(){
     console.log('link clicked');
     
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mySomething"></div>

Something like this?

歐津柏
  • 94
  • 5