在Jquery中使用php变量,作为动态创建的背景图像

时间:2018-06-08 12:22:44

标签: php jquery

我已经看过一些类似的帖子,但我认为我的情况有所不同。 我有以下代码:

$(".imagem .bottom-buttons").on("click", ".ver-emb", function(event){
        var Image = <?php echo $row->embalagem; ?>;
//row-embalagem comes from a query search to the database.
        $(".slider-img").css("background-image", "url(../assets/imagens/<?php echo $row->embalagem; ?>)");
        $(this).addClass( "ver-prod" );
        $(this).removeClass( "ver-emb" );
        $(this).text( "Ver Produto" );
    });

我已经读过您需要将php变量放入jquery变量,但是如何将新的Jquery变量应用于background-image url?

3 个答案:

答案 0 :(得分:1)

试试这个:

$(".imagem .bottom-buttons").on("click", ".ver-emb", function(event){
            var Image = '<?php echo $row->embalagem; ?>';
    //row-embalagem comes from a query search to the database.
            $(".slider-img").css("background-image", "url(../assets/imagens/"+image+")");
            $(this).addClass( "ver-prod" );
            $(this).removeClass( "ver-emb" );
            $(this).text( "Ver Produto" );
        });

答案 1 :(得分:1)

您使用它的方式与在JavaScript中使用任何变量的方式相同:

"url(../assets/imagens/" + Image + ")"

此外,如果您的变量是一个字符串(您将其用作字符串),那么字符串需要用引号括起来:

var Image = "<?php echo $row->embalagem; ?>";

答案 2 :(得分:1)

只需在网址中附加Image var,就像这样:

$(".imagem .bottom-buttons").on("click", ".ver-emb", function(event){
    var Image = "<?php echo $row->embalagem; ?>";
    $(".slider-img").css("background-image", "url(../assets/imagens/"+Image+")");
    $(this).addClass( "ver-prod" )
    $(this).removeClass( "ver-emb" );
    $(this).text( "Ver Produto" );
});