如何使用jquery将文本添加到现有div

JSt*_*JSt 54 html jquery text add

当我单击ID为#add的Button时,我想将文本添加到现有div中.但这不起作用.

这是我的代码:

$(function () {
  $('#Add').click(function () {
    $('<p>Text</p>').appendTo('#Content');
  });
}); 
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <div id="Content">
    <button id="Add">Add</button>
 </div>
Run Code Online (Sandbox Code Playgroud)

我希望你能帮助我.

bre*_*rer 56

您需要定义按钮文本并为按钮提供有效的HTML.我还建议使用.on按钮的单击处理程序

$(function () {
  $('#Add').on('click', function () {
    $('<p>Text</p>').appendTo('#Content');
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="Content">
    <button id="Add">Add Text</button>
</div>
Run Code Online (Sandbox Code Playgroud)

另外,我会确保jquery位于结束</body>标记之前的页面底部.这样做会使你不必将整个东西包裹起来,$(function但我仍然会这样做.在页面末尾加载javascript会使页面的其余部分加载,因为某些地方的javascript速度会变慢.

  • jquery `.replaceWith()` 方法通过一次调用从 DOM 中删除内容并在其位置插入新内容。`$( "div.second" ).replaceWith( "&lt;h2&gt;新标题&lt;/h2&gt;" );` [jquery api](http://api.jquery.com/replaceWith/) (2认同)

Zac*_*dev 11

HTML

//If you want add the element before the actual content, use before()
$(function () {
  $('#AddBefore').click(function () {
    $('#Content').before('<p>Text before the button</p>');
  });
});

//If you want add the element after the actual content, use after()
$(function () {
  $('#AddAfter').click(function () {
    $('#Content').after('<p>Text after the button</p>');
  });
});
Run Code Online (Sandbox Code Playgroud)

如果你想要在buttom之后

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

<div id="Content">
<button id="AddBefore">Add before</button>
<button id="AddAfter">Add after</button>
</div>
Run Code Online (Sandbox Code Playgroud)

或之前

//If you want add the element before the actual content, use before()
$(function () {
  $('#AddBefore').click(function () {
    $('#Content').before('<p>Text before the button</p>');
  });
});

//If you want add the element after the actual content, use after()
$(function () {
  $('#AddAfter').click(function () {
    $('#Content').after('<p>Text after the button</p>');
  });
});
Run Code Online (Sandbox Code Playgroud)


Mus*_*usa 5

您的html无效button不是空标记.尝试

<div id="Content">
   <button id="Add">Add</button>
</div> 
Run Code Online (Sandbox Code Playgroud)