简体   繁体   中英

Load an HTML file via a button using jQuery

I am trying to call a HTML file when a button is clicked using jQuery.

Here is my html code:

<!DOCTYPE html>
<head>

    <title>Buttons</title>

    <script type="text/javascript" src="jquery-1.3.2.js"></script>
    <script type="text/javascript" src="buttonscript.js">
    </script>
</head>
<body>  
<input type ="button" id="myButton" value="Click Here">

<div id="dictionary">
</div>
</body>
</html> 

then here is my script:

$(document).ready(function(){
    $('myButton').click(function(){
        $('dictionary').load('a.html');
        return false;
    });
  });

You have two wrong things in your script:

  1. You are not assigning the selectors with the right syntax;
  2. You are using document ready syntax on an external file;

The first point is fixed using # before the id name and . before the class name (see below the fix).

The document.ready() function should be included into the html itself: it tells jquery to run the script only when the DOM is ready. Including it in an external file will make jQuery check for DOM ready on the external file and not on the one you are including to. So move your script to the html itself and change it a bit:

.

$(document).ready(function(){
    $('#myButton').click(function(e){
    // prevent page submit
        e.preventDefault(); 
        // load the page into #dictionary
        $('#dictionary').load('a.html');
    });
});

Add # to your selectors like, and instead of using return false , you could prevent default behavior of the button (if the type attribute is set to submit ).

$(document).ready(function(){
    $('#myButton').click(function(event){

        // prevent page submit
        event.preventDefault(); 

        // load the page into #dictionary
        $('#dictionary').load('a.html');

    });
});

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