简体   繁体   中英

Click event not working properly

I have a problem with click event:

I have in HTML:

<div class="content-block cards-clipboard">
                        <a class="download-all">Download All</a>

                        </div>

And a JS:

var html = '<div class="card demo-card-header-pic data-url='+img+'">'+
  '<div style="background-image:url('+thumb+'); background-size: 100%; height: 272px; background-repeat: no-repeat;" valign="bottom" class="card-header color-white no-border">'+html_icone_camera+'</div>'+
  '<div class="card-content">'+
    '<div class="card-content-inner">'+
     '<p class="color-gray">Postado em '+datapub+'</p>'+
      '<p>'+legenda+'</p>'+
    '</div>'+
  '</div>'+
  '<div class="card-footer-'+id_link+'">'+
    '<button data-url='+img+' data-step="download" data-cod='+id_link+' type="button" class="download-imagem btn btn-primary btn-lg btn-block '+id_link+'"><i class="fa fa-download" aria-hidden="true"></i>&nbspDownload</button>'+
  '</div>'+
'</div>';

$$(html).appendTo('.cards-clipboard');  

And a trigger:

$$('.download-all').on('click', function() {
                $$("button[data-step='download']").click();

            });

That is: I have a button ('.download-all') when clicked, trigger a click in other buttons generated dinamically via append (var html) that have the data-step=download attribute.

However, when i click in .download-all button, the first button not receive a click - only the first button - the others, receive....

I appreciate any help

EDIT : If i put $$("button[data-step='download']").click(); in console, the clicks works fine in all buttons....

If you are using jQuery, remove 2 $ signs and only have one:

$(html).appendTo('.cards-clipboard');  

And your event command would be:

$('.download-all').on('click', function() {
            $("button[data-step='download']").trigger('click');

        });

Try to use JQuery trigger()

 $$('.download-all').on('click', function() {
            $$("button[data-step='download']").trigger("click");

 });

If not try to remove the double dollar sign and use single dollar sign.

Please vote and mark the solution if useful.

Thanks!

Only the first button is being triggered because of page loading order. php is executed before html/javascript. Because this happens, the event handler can't find a button with specified id or class. One way to circumvent this is to delegate an event listener to the area which contains the dynamically created buttons. For instance,

$('#myId').delegate('button','click',function() {
       //do something
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM