0

I've got troubles, tried everything but variable always undefined =/

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#show").load("index.php");
        });
        $(document).on('click', ' a[href]', function (e) {
            var a_href = $(this).find('a').attr('href');
            alert ("Href is: "+a_href); //just for test
           $("#show").load(a_href);
           return false;
        }); 
    </script>
</head>
<body>
<a href="one.php">One</a>
<br>
<a href="two.php">two</a>

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

I actually want links to be taken from #show div and replace show div load after it without changing the link or reloading the page, the links are generated in php and always change this is why i cant have static links.

1
  • You seem to be looking for an anchor tag inside the anchor tag you clicked, try removing the .find('a') Commented May 6, 2016 at 21:02

2 Answers 2

2

You already select the link with .on('click', ' a[href]', so $(this).find('a') is looking for a link that's a descendant of the link that you clicked on, which doesn't exist.

Change:

$(this).find('a').attr('href')

to

$(this).attr('href') // jQuery

or

this.href // plain JavaScript as noted by epascarello 
Sign up to request clarification or add additional context in comments.

3 Comments

15 seconds faster than me.
How can i set it up working links only from #show div ?
It should be noted that this.hrefreturns the full/resolved path, but $(this).attr('href') or this.getAttribute('href') returns the original attribute value.
0

I would use this:

  .... your code
$('a').click(function (e) {
    var a_href = $(this).attr('href');
  .... your code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.