简体   繁体   中英

jQuery variable undefined with php include

I am trying to use a variable in jQuery wich is included with php, the attr rel of the img in footer.

I try to use it to change the attr src in that same img in footer.

if I use it without include, then it works. But with include it doesn't.

I always get ../img/undefined.svg as a result.

How can I get it to be ../img/facebook.svg or ../img/twitter.svg ?

In my php-file I use:

<?php include '../include/header.php';?>
<?php include '../include/footer.php';?>

In header.php is javascript, jQuery and html:

    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" type="text/css" href="../css/stijl.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("footer img").hover(
            function(){
                var src = $(this).attr('rel');
            $(this).attr('src', '../img/' + src + '-n.svg');
                }
        ,
        function(){
            var src = $(this).attr("rel");
            $(this).attr('src', '../img/' + src + '.svg');
        }
        );
    });
</script>

In footer.php is just html:

    <footer>
    <div class="content">
        <a rel="twitter" href="#">
            <img src="../img/twitter.svg">
        </a>
        <a rel="facebook" href="#">
            <img src="../img/facebook.svg">
        </a>
    </div>
</footer>

$(this) refers to the img tag, which has no rel attribute. Its parent tag, however, does. Try:

var src = $(this).parent().attr('rel');

or if the markup may change slightly, this may be more robust:

var src = $(this).closest('a').attr('rel');

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