Javascript 使用javascript在另一个元素内创建一个span元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5802663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a span element inside another element using javascript
提问by Nicekiwi
This code is from google calender.
此代码来自谷歌日历。
var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
if (!startDateTime.isDateOnly()) {
dateString += " @ " + startJSDate.getHours() + ":" +
padNumber(startJSDate.getMinutes());
}
dateString = "<span>" +dateString + "</span>";
var li = document.createElement('li');
I need to add a span tag around the variable dateString, adding them as above returns "1234" as text on the page.
我需要在变量 dateString 周围添加一个 span 标记,将它们添加为上述返回“1234”作为页面上的文本。
The string is rendered as such:
字符串呈现如下:
li.appendChild(document.createTextNode(' - ' + dateString));
回答by Naren Sisodiya
Try following code, create span using createElement and insert date string in it as innerHTML. Then append span to li.
尝试以下代码,使用 createElement 创建跨度并在其中插入日期字符串作为innerHTML。然后将跨度附加到 li。
var dateSpan = document.createElement('span')
dateSpan.innerHTML = dateString;
var li = document.createElement('li');
li.appendChild(dateSpan);
回答by Reporter
if you can use jquery, then the method .wrap() will do it what you want.
如果您可以使用 jquery,那么 .wrap() 方法将按照您的意愿进行操作。