Emmet B
Emmet B

Reputation: 5541

.click() does not work on a span class that loaded later

In my main page I have a "music" button, it loads music.txt

script.js

$("#music").load("music.txt");
$('.song').click(function () {  ... });

music.txt:

 <span class="song"> bl </span>

$('.song').click does not work on music.txt (it works on mainpage). I tried live() and delegate() as well.

Upvotes: 2

Views: 288

Answers (1)

Dipesh Parmar
Dipesh Parmar

Reputation: 27382

Use .on() jQuery method.

$('.song').on('click',function () { /*...*/ });

OR

$(document).on('click','.song',function(){ /*...*/ });

because .live() is deprecated from newer version.

In first example the .on() method behaves similar to bind and will only work on elements that already exist.

The second example behaves like .live() or delegate() in many ways. And will work for elements that are added later.

Upvotes: 8

Related Questions