简体   繁体   English

如何定义javascript变量作为div的ID?

[英]How do I define a javascript variable as a div's id?

I am trying to define a var equal to the id of a div in the body. 我正在尝试定义一个等于正文中div的id的var。 My non-functional idea was this: 我的非功能性想法是这样的:

var userid = $('.all').attr('id');

Since I need the variable to be defined as the id as soon as the page loads, I am not using an event and cannot use a technique like: 由于我需要在页面加载后立即将变量定义为id,因此我没有使用事件,也无法使用类似的技术:

$('.all').click(){
  var alldivIDvalue = $(this).attr('id');
}

Not sure if it makes a difference, but the id will equal a php output of sessions profile/username. 不知道这是否有所作为,但是ID等于会话配置文件/用户名的php输出。

Propably you should declare somewhere in the top of your page (even in head) var userid and then after document.load append value to this variable. 可能您应该在页面顶部的某个位置(甚至在头部)声明var userid,然后在document.load之后将值附加到此变量。

var userid = []; //In html head

Then inside your jquery load: 然后在你的jQuery加载:

$(document).ready(function () {
    userid = $('.all').attr('id');
});

Place where you put load doesnt matter and doesnt affect on other html bacause this event is triggered when html document is loaded. 放置负载的位置无关紧要,也不会影响其他html,因为加载html文档时会触发此事件。

Edit 编辑

Thanks for comment. 感谢您的评论。

If the id is known to PHP at the time the page's HTML is built, then you can write it directly into javascript like this: 如果在构建页面的HTML时PHP知道该ID,则可以将其直接写入javascript,如下所示:

<script>
var userid = '<?php echo $userID; ?>';
</script>

When available, this approach is more straightforward than writing a value into the HTML server-side (and thence the DOM) then reading it into javascript client-side. 如果可用,此方法比将值写入HTML服务器端(然后是DOM)然后将其读取到javascript客户端更为直接。

Of course, there's nothing to stop you writing the same value into the HTML/DOM for some other purpose. 当然,没有什么可以阻止您将相同的值写入HTML / DOM用于其他目的。

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

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