将 html 放在 javascript 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10381681/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:06:20  来源:igfitidea点击:

place html in javascript?

javascripthtmlhyperlinkdom-manipulation

提问by user840930

I need to place html in javascript. Specifically, I would like to add an HTML link to a div tag with javascript.

我需要将 html 放在 javascript 中。具体来说,我想用 javascript 添加一个 HTML 链接到一个 div 标签。

html:

html:

<div id="mydivtag"></div>

javascript:

javascript:

document.getElementById('mydivtag').innerHTML = "<li><a href=\"someLink\">Some Link</a></li> ";

Am I formatting the html link I am adding through javascript correctly?

我是否正确格式化了通过 javascript 添加的 html 链接?

回答by Andy Gaskell

Looks fine and works here. You may want to consider mixing single quotes instead of escaping the double quotes, but that's just a preference.

看起来不错,在这里工作。您可能需要考虑混合单引号而不是转义双引号,但这只是一种偏好。

document.getElementById('mydivtag').innerHTML = "<li><a href='someLink'>Some Link</a></li>";

回答by Amberlamps

You can have it in one line:

您可以在一行中使用它:

document.getElementById("mydivtag").appendChild(function(li, l, t) { li.appendChild(function(a, l, t) { a.href = l; a.innerHTML = t; return a; } (document.createElement("a"), l, t)); return li; } (document.createElement("li"), "mylink", "mytext"));

回答by Petah

It needs more jQuery:

它需要更多的jQuery:

$('#mydivtag').html('<li><a href="someLink">Some Link</a></li>');