在html()中标记div

时间:2018-12-26 06:28:55

标签: jquery

如果我在html()内使用div标签设置内容,然后再将其放入div标签,这意味着我现在在id = test中有两个div标签?如果在html()中使用标签h1进行设置,然后再将其放置到标签h1中怎么办?

  $(document).ready(function(){
     $("#btn").click(function(){
         $("#test").html("<div>Hello world!<div>");
     });
  });

这是标记div

 <div id="test"></div>

 <button id="btn">click</button>

2 个答案:

答案 0 :(得分:1)

您可能会找到它:

您还设置了其他条件,并且必须学习'text,html,append,prepend'(在此处学习链接https://www.w3schools.com/jquery/jquery_dom_add.asp

 var counter=0;
 $(document).ready(function(){
   $("#btn").click(function(){
     if(counter==0){
      $("#test").append("<div>Hello world!<div>");
     }else if(counter==1) {
      $("#test").append("<h1>Another heading 1<h1>");
     }else if(counter==2) {
      $("#test").append("<h2>Another heading 2<h2>");
     }
     counter+=1;
   });
  });
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
  
 <div id="test"></div>
 <button id="btn">click</button>

答案 1 :(得分:0)

无论您在.html()内部添加什么内容,都将显示在element内部。

http://jsfiddle.net/brahmpragya/wqret2p4/2/

HTML

<div id="test"></div>
<div id="test1"></div>
<button id="btn">click</button>

JS

 $(document).ready(function(){
   $("#btn").click(function(){
   $("#test").html("<div>Hello world!</div>");
   //h1 inside the .html
   $("#test1").html("<h1>Hello world!</h1>");
   });
  });
相关问题