douhu2525 2015-06-13 20:35
浏览 71
已采纳

用php包含的jQuery变量未定义

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>
  • 写回答

1条回答 默认 最新

  • dongshi1102 2015-06-13 20:38
    关注

    $(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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch