简体   繁体   中英

Replacing html page text by using JQuery

I have a simple javascript code which replaces the page content....by contents of another file(test2.html)

Code:

$(document).ready(function(){
    $("[href='#']").click(function() {
        function getcontent(url, id) {
            $("#id").load("url");
        }
    });
});

Now am using

<div id = "content">                 
<p> REPLACE </p>
</div>
<a href="#" onClick="getcontent('test2.html', 'content')">click here</a> 

So now on clicking click here REPLACE should be replaced by content of test2.html ...but its not happening... I have included the required jquery.js file in my script..

No, this won't work. getcontent is a function defined in a particular scope -- that of the click handler callback function. It is not accessible in the global scope -- the scope that the onClick method receives.

You should use a genuine click handler, perhaps setting data using data attributes:

$('[href="#"]').click(function() {
    $('#' + $(this).data('id')).load($(this).data('url'));
});

Using the following HTML:

<a href="#" data-url="test2.html" data-id="content">click here</a>

You have a weird setup. The function getcontent is not defined in global scope, it cannot be found by the onclick event handler in the HTML. There are other issues as well.

I suggest something like:

<a href="#content" rel="test2.html">click here</a> 

and

$(function(){
    $("a[href^='#']").click(function(){
        $(this.href).load(this.rel);
    });
});
$('#' + id).load(url);

In your current method above, you are passing string literals, not the variables themselves.

You seem to be misunderstanding what certain parts of your code are doing. Also, I'd recommend giving your href a real id to make things easier. You don't need to use the jQuery 'click' method and ALSO assign an onclick handler inline in the HTML.

Try this instead:

<div id = "content">                 
   <p> REPLACE </p>
</div>
<a id="clickThis" href="#">click here</a>

$(document).ready(function() {
    $('#clickThis').click(function() {
       $('#content').load('test2.html');
    });
});

Your code with some comments:

$(document).ready(function(){
    // this will assign a click handler, you don't need an 'onclick'
    // attribute on the anchor tag also
    $("[href='#']").click(function() {
        // but what does your click handler do?
        // It defines a function that is never called.
        function getcontent(url, id) {
            $("#id").load("url");
        }
    });
});

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