简体   繁体   English

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

[英]is it possible to dynamically assign ID to an element in webpage using JS/ PHP?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage? 是否可以在网页运行期间像动态设置元素ID一样以编程方式设置元素的ID?

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. 现在,我想使用php代码中变量的值来动态设置此元素“ body”的ID。 Is this possible? 这可能吗? something like - 就像是 -

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

I use php and jquery in the page; 我在页面中使用php和jquery; please let me know whether such dynamic id assignment is possible to the elements in the html. 请让我知道是否可以对html中的元素进行这种动态id分配。

thanks. 谢谢。

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

gives (with jquery) 给(与jQuery)

<body id="insert_id">

PHP is the background language, it's what produces your HTML output. PHP是背景语言,它是产生HTML输出的要素。 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输出的任何内容最终都会变成HTML,这是的,您可以将PHP变量用作您的elemnt-ID或其他任何方式。

<?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. 或您可以使用单个echo语句输出所有HTML。

<?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... 总之,PHP完成执行后剩下的就是最终用户浏览器解释的HTML代码...希望对您有所帮助...

Why not? 为什么不? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts. 只要将随机化器(Math.rand)保持足够大,冲突的机会就很小。

I usually do this, and then at the same time call a JS method and passing the same ID. 我通常这样做,然后同时调用JS方法并传递相同的ID。 That would require you storing the ID aside so you can pass it later. 这将需要您将ID放在一旁,以便以后再传递。

Edit: If you are only setting this on the body then you would not need to access it later. 编辑:如果仅将其设置在主体上,则以后无需访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM