jquery - Cannot execute action on added elements (added on the run using jquery) -


my idea create button show multiple text, , when click on text, added in textbox

my code showing multiple text suitable :

$("#btnlook").click(function(){     $.ajax({    ...         success: function(data1) {         for( var = 0; < data1.length; i++ )             {             var spn = '<span class ="spnsuggestion" id="data1[' + + ']">' + data1[i] + '</span>';              $("#divsuggestion").html($("#divsuggestion").html() + '  ' + spn);             }         },    ...   }); 

and function clicking text

  $(".spnsuggestion").click(function(){     alert ("a"); 

but code not running, , not showing alert box, solution please

$(".spnsuggestion") returns elements match selector when call it. not account new elements.

to account new elements, use event delegation:

$('#divsuggestion').on('click', '.spnsuggestion', function() {     ... }); 

also, don't abuse .html(). make jquery object , append it:

$('<span class ="spnsuggestion" id="data1[' + + ']">' + data1[i] + '</span>').appendto('#divsuggestion'); 

or:

$('<span>', {     'class': 'spnsuggestion',     'id': 'data1[' + + ']',     'text': data1[i] }).appendto('#divsuggestion'); 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -