简体   繁体   中英

Using PHP to insert a HTML tag

I have this HTML tag (body):

<body onload="startTime()" background="src/bg3.png">

and I was trying to change background on refresh so I replaced the HTML tag with this PHP code:

<?php
    $id = rand(1, 7);
    echo "<body onload=".'"'."startTime()".'"'."background=".'"'."src/bg". $id . ".png".'"'.'>';
?>

which returns:

<body onload="startTime()" background="src/bg5.png">

where the number after bg is a random between 1 and 7.

But the problem is that when I inspect element the body tag is simply:

<body>

Does PHP only allow HTML code insertion if it's being returned by a function?

seems you have some problem with quotes ..

<?php
    $id = rand(1, 7);
    echo "<body onload='startTime()' background='src/bg". $id . ".png'>";
?>

Try:

echo "<body onload='startTime()' style='background:url('src/bg{$id}.png')>";

Your sting was hard to follow but I think you messed up the concatenation.

Background is part of a style tag. I made the Id part of string interpolation rather than more concates and putting single quotes in double works.

Decided to try using a function again (already tried but didn't work):

    function changeBG() {
        //generate a random number from min to max
        var min = 1, max = 7;
        var str1 = "src/bg", str2 = ".png"
        var number = Math.floor(Math.random() * max) + min;
        var path = str1.concat(number);
        path = path.concat(str2);
        document.body.background = path;
    }

This solved it, thanks to everybody that helped.

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