简体   繁体   中英

button imported with get function doen't work

I have a problem with a button imported in a HTML file using JQUERY and get function. I'm trying to check if it is clicked or not but i don't know why i can't print anything to the console. I imported the button using this script:

          $.get( "nuovotaglio.html", function( data ) {

              var newDiv = $('<div/>',{id:'Servizio'+ incremento}).appendTo('.nuovoServizi');

              newDiv.html(data);

              var idInputeText = newDiv.children().children().find("input[name='servizio']");
              idInputeText.attr('id','input'+incremento);

          });

then I wrote

        $(function() {
           $('button').click(function(){
            console.log('ciao');
            });
        });

I also tried

    $('button').click(function(){
        console.log('ciao');
    });

also this script doesn't work

        $('button').on('click', function(event) {
            console.log('ciao');
        });

does someone know how to check an events from an HTML code imported using GET?

Your problem is likelly in adding an element to the page AFTER you fire the ready JQ function.

Rewriting your JQ code to the following should fix it.

    $(document).on('click', 'button', function(event) {
        console.log('ciao');
    });

Alternativelly, if stuff is still bugging out, you can try (yes, I have actually seen that bug out for some reason once, so here is solution B if needed)

    $('body').on('click', 'button', function(event) {
        console.log('ciao');
    });

When the the second script initialized then there was no button at that moment. That's why the click event didn't worked.

Load this script after successfully load the content.

You may use

$(document).ready(function() {
   // second script here
});

Or you can use:

$.ajax({
   url: "test.html",
   method: "GET",
   data: { id : $( "ul.nav" ).first().attr( "id" ) },
   dataType: "html",
   success: function() {
       $('button').click(function(){
           console.log('ciao');
       });
   }
});

If you have more file or portion of code to import in your HTML and Javascript or Jquery doesn't work try also using PHP instead of HTML.

Rename your file with PHP extension and upload your file on a real server or virtual server like MAMP or XAMP).

Then use this sintax to import your file:

<?php  include("your_file_path/your_file_name.html");  ?>

I tried to include a big section of a website inside the mainpage and my other HTML file was in the same folder of the HOMEPAGE. I used

<?php  include("section6.html");  ?>

After use this method all my Jquery library worked correctly.

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