最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Setting a JS variable and using it in html tag - Stack Overflow

programmeradmin5浏览0评论

I have set a variable, and I need to pull in this variable into a html element, but I cant get it to print out the value, this is the code:

<script>
    var randomnumber=Math.floor(Math.random()*11)
</script>

<div id="<script type="text/javascript">document.write(randomnumber)</script>"></div>

Thanks.

Edit: I just used a div as an example, but i need to add a random number to an img tag, as it is for a tracking tag, and needs a unique identifier. Is there a better way to go about this?

I have set a variable, and I need to pull in this variable into a html element, but I cant get it to print out the value, this is the code:

<script>
    var randomnumber=Math.floor(Math.random()*11)
</script>

<div id="<script type="text/javascript">document.write(randomnumber)</script>"></div>

Thanks.

Edit: I just used a div as an example, but i need to add a random number to an img tag, as it is for a tracking tag, and needs a unique identifier. Is there a better way to go about this?

Share Improve this question edited Dec 11, 2012 at 13:03 treasureireland asked Dec 10, 2012 at 18:08 treasureirelandtreasureireland 872 gold badges3 silver badges10 bronze badges 4
  • 3 What is this for? Why assign a random ID to an element? (Numeric-only IDs are invalid in HTML 4 btw) – Pekka Commented Dec 10, 2012 at 18:09
  • 1 Just inject the div via javascript itself. Btw in html4 you shouldn't have leading numeric id's – aziz punjani Commented Dec 10, 2012 at 18:11
  • And I'm not even sure you can put script tags inside attributes... – Ian Commented Dec 10, 2012 at 18:11
  • 2 document.write? In the end of 2012? – raina77ow Commented Dec 10, 2012 at 18:12
Add a ment  | 

2 Answers 2

Reset to default 8

Use

<script>
document.write('<div id="'+randomnumber+'" ></div>');
</script>

You can't open a script tag inside an attribute

Or you can create it using JS:

var randomnumber=Math.floor(Math.random()*11);
a = document.createElement('div');
a.setAttribute('id',randomnumber);
document.body.appendChild(a);

// if you know the exact class or ID where it is to be appended you can use

document.getElementsByClassName("myclass")[0].insertBefore(a, document.getElementsByClassName("beforeClass").firstChild);

This will create a div, with the id as the randomnumber and append it to the body

发布评论

评论列表(0)

  1. 暂无评论