RanRag
RanRag

Reputation: 49537

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..

Upvotes: 0

Views: 282

Answers (4)

Mike Edwards
Mike Edwards

Reputation: 3763

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");
        }
    });
});

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816232

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);
    });
});

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237817

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>

Upvotes: 1

Matt
Matt

Reputation: 339

$('#' + id).load(url);

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

Upvotes: 0

Related Questions