用php包含的jQuery变量未定义

时间:2015-06-13 20:35:40

标签: php jquery html

我试图在jQuery中使用一个变量,包含在php中, 页脚中的img的attr rel。

我尝试用它来改变页脚中相同img的attr src。

如果我在没有包含的情况下使用它,那么它可以工作。 但是包含它不会。

我总是得到../img/undefined.svg。

我怎样才能将它变为../img/facebook.svg或../img/twitter.svg?

在我的php文件中,我使用:

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

在header.php中是javascript,jQuery和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>

在footer.php中只是html:

def comment_author
  "#{user.firstname} #{user.lastname}"
end

1 个答案:

答案 0 :(得分:0)

$(this)引用img标记,该标记没有rel属性。但它的父标签确实如此。尝试:

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

或者如果标记可能略有变化,这可能会更加强大:

var src = $(this).closest('a').attr('rel');
相关问题