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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3