简体   繁体   中英

Dynamically create HTML in Javascript using JS variables within HTML tags

I am trying to dynamically create HTML code with JavaScript using JS variables in the HTML tags. The code is then inserted into my HTML file via .innerHTML .

What isn't working (I didn't expect it to work really, but I'm not sure how to force it to work) is setting the id and margin-right attributes to JS variables (using dynamicID and equalMargin respectively).

 var numberOfImages = 7 var equalMargin = 1; //(divElement.clientWidth - equalWidth*7) / 6; var dynamicCode = ""; var dynamicID = ""; var i; for(i = 0; i < numberOfImages - 1; i++) { dynamicID = "navDot" + i + ""; console.log(dynamicID); dynamicCode = dynamicCode + '<img src = "https://dl.dropboxusercontent.com/s/mvj24qzluobu098/seekDotEmpty.png?dl=0" alt = "emptyDot" id = dynamicID style = "max-height: 100%; margin-right = equalMargin;">'; } 

Just end the string, add the variable, and reopen the string.

Also, there are no spaces between attributes, the equals ( = ) sign and their values.

 var numberOfImages = 7 var equalMargin = 1; //(divElement.clientWidth - equalWidth*7) / 6; var dynamicCode = ""; var dynamicID = ""; var i; for(i = 0; i < numberOfImages - 1; i++) { dynamicID = "navDot" + i + ""; console.log(dynamicID); dynamicCode = dynamicCode + '<img src="https://dl.dropboxusercontent.com/s/mvj24qzluobu098/seekDotEmpty.png?dl=0" alt="emptyDot" id="' + dynamicID + '" style="max-height: 100%; margin-right: ' + equalMargin + ';">'; } 

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