是否可以使用JS / PHP动态地为网页中的元素分配ID?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage?

Consider this scenario -

<body id="body1">

Now, i want to set the id of this element "body" dynamically, using the value of a variable in the php code. Is this possible? something like -

<body id=" <?php echo $bodyID; ?> ">

I use php and jquery in the page; please let me know whether such dynamic id assignment is possible to the elements in the html.

thanks.

PHP is the background language, it's what produces your HTML output. So basically, what ever you output from PHP eventually becomes your HTML, meaning yes you can use PHP variables as your elemnt-ID or anything else for that matter.

<?PHP
$var = "body1";
?>
<body id="<?PHP echo $var; ?>"> Hello my ID is <?PHP echo $var; ?></body>

OR You can output all of the HTML using a single echo statement.

<?PHP
$var = "body1";
echo "<body id='$var'>Hello my ID is $var</body>";
?>

In conclusion, whatever is left after PHP is finished executing is your HTML code that the end users browser interprets... Hope this helps...

$(function() {
    var variable = 'insert_id';
    $('body').attr('id', variable);
});

gives (with jquery)

<body id="insert_id">

Why not? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts.

I usually do this, and then at the same time call a JS method and passing the same ID. That would require you storing the ID aside so you can pass it later.

Edit: If you are only setting this on the body then you would not need to access it later.