javascript - 为什么我得到这个输出? ( jQuery .append() 问题)

标签 javascript jquery css

为什么 append 在这里的行为完全不同..任何人都可以解释一下!

最近在练习 jQuery 时卡在了这里,不明白发生了什么:在第一次单击按钮时,元素按预期正常添加,但在第二次单击时/之后,东西(输出)开始变得奇怪。有人可以解释一下这里发生了什么吗...
我是 jQuery 的新手。

function appendText() {
  var txt1 = "<p id='set'>Text1</p>";
  console.log("Text1", txt1);

  var txt2 = $("<p></p>").text("Text2");
  console.log("Text2", txt2);

  var txt3 = document.createElement("p");
  txt3.innerHTML = "Text3";
  console.log("Text3", txt3);

  var txt4 = $("#set").html("Text4");
  console.log("Text4", txt4);

  $("body").append(txt1, txt2, txt3, txt4);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Append Test Example</p>
<button onclick="appendText()">Append text</button>

Output Image

最佳答案

试试这个?

var ourButton = document.getElementById("btn");
    
var ourList = document.getElementById("our-list");

ourButton.addEventListener("click",func2);

newAddedText = 1;

function func2() {
  ourList.innerHTML += "<li>anything " + newAddedText + "</li>";
  newAddedText++;
}
<button id="btn">Add New</button>
<ul id="our-list">
</ul>

关于javascript - 为什么我得到这个输出? ( jQuery .append() 问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53668804/

相关文章:

javascript - 如何保持 float div 在窗口调整大小时居中 (jQuery/CSS)

html - 为什么创建顶部 div 会在底部增加空间?

javascript - IE6 中的出生日期选择器问题

javascript - 如何在 PHP 中获得丰富的控件?

jquery - 如何构建具有多个图像切换的文档

css - 如何使用 Angular 2+ 指令从选项卡自定义背景颜色?

html - 如何防止图像在加载时移动内容?

javascript - 如何将参数传递给 Mongo 脚本

javascript - 我应该使用内联还是有线事件处理程序

javascript - fullpage.js - 如果 'scrolloverflow' 设置为 true 则无法向下滚动到下一部分