icebp
icebp

Reputation: 1709

JQ event handler on a click

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.

Upvotes: 2

Views: 166

Answers (3)

歐津柏
歐津柏

Reputation: 94

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?

Upvotes: 0

l1e3e3t7
l1e3e3t7

Reputation: 118

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.

Upvotes: 3

Amar Singh
Amar Singh

Reputation: 5622

delegated event must work

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

alert("yes")

} );

Upvotes: 1

Related Questions