HTML标题不会彼此相邻显示?

时间:2015-03-27 17:07:23

标签: javascript jquery html

我试图展示两个标题,但它们并没有显示出来。 我单独测试它们并且它们起作用但结合起来它没有用。

$("html").html("<h1 style='position:absolute;left:20%;color:green;'>test1</h1>"); // load1

$("html").html("<h2 style='position:absolute;left:60%;color:green;'>test2</h2>"); // load2

2 个答案:

答案 0 :(得分:1)

那是因为你第二次使用html()覆盖了第一个标题。在第二种情况下使用append()

&#13;
&#13;
$("html").html("<h1 style='position:absolute;left:20%;color:green;'>test1</h1>"); 
$("html").append("<h2 style='position:absolute;left:60%;color:green;'>test2</h2>");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

或者将新标题添加到旧的html:

&#13;
&#13;
$("html").html("<h1 style='position:absolute;left:20%;color:green;'>test1</h1>"); 
$("html").html($("html").html()+"<h2 style='position:absolute;left:60%;color:green;'>test2</h2>");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

https://api.jquery.com/html/

  

当.html()用于设置元素的内容时,该元素中的任何内容都将被新内容完全替换。

你用第二个标题覆盖第一个标题。请尝试使用append(),这会添加到元素中。在vanilla JS中,你会innerHTML += "more html here";

另一方面,不鼓励使用innerHTML(vanilla JS)或.html()(jQuery)。