如何使用jQuery将文本添加到现有的div [英] How to add text to an existing div with jquery

查看:76
本文介绍了如何使用jQuery将文本添加到现有的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击ID为#add的按钮时,我想将文本添加到现有div。但是这不起作用。



这里是我的代码:

  $(function(){$('#Add')。click(function(){$('< p> Text< / p>)。appendTo('#Content');}); });  

< script src =https:// ajax。 googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script> < div id =Content> < button id =Add/>



我希望你能帮助我。

解决方案

您需要定义按钮文本并为该按钮设置有效的HTML。我还建议使用 .on 作为按钮的点击处理程序

 

< script src =https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js>< / script>< div id =Content > < button id =Add>添加文本< / button>< / div>

另外,我会确保jquery在结束< / body> 标记之前的页面底部。这样做可以让你不必将整件事情都包装在 $(function >中,但我仍然会这样做。使得它的页面的其余部分加载incase有一个放缓你的JavaScript的地方。


I want to add text to an existing div, when I click the Button with the id #add. But this is not working.

Here my code:

$(function () {
  $('#Add').click(function () {
    $('<p>Text</p>').appendTo('#Content');
  });
}); 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <div id="Content">
    <button id="Add" />
 </div>

I hope you can help me.

解决方案

You need to define the button text and have valid HTML for the button. I would also suggest using .on for the click handler of the button

$(function () {
  $('#Add').on('click', function () {
    $('<p>Text</p>').appendTo('#Content');
  });
});

<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>

Also I would make sure the jquery is at the bottom of the page just before the closing </body> tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.

这篇关于如何使用jQuery将文本添加到现有的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆