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

查看:17
本文介绍了如何使用 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="内容"><button id="添加">添加</button>

我希望你能帮助我.

解决方案

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

$(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="内容"><button id="Add">添加文本</button>

此外,我会确保 jquery 位于页面底部的 </body> 标记之前.这样做将使您不必将整个内容都包含在 $(function 中,但我仍然会这样做.在页面末尾加载 javascript 可以使其余部分页面加载,以防您的 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">Add</button>
 </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天全站免登陆