How to add text to an existing div with jquery

2019-01-16 23:08发布

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.

6条回答
The star\"
2楼-- · 2019-01-16 23:21

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

查看更多
来,给爷笑一个
3楼-- · 2019-01-16 23:23

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-01-16 23:23

Html

<div id="Content">
<button id="Add" value="Add" />
</div> 

if you want after the buttom

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

or before

$(function () {
  $('#Add').click(function () {
    $('#Content').before('<p>Text</p>');
  });
}); 
查看更多
地球回转人心会变
5楼-- · 2019-01-16 23:24

Very easy from My side:-

<html>
<head>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("input").click(function() {
            $('<input type="text" name="name" value="value"/>').appendTo('#testdiv');
        });

    });
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <div id="testdiv"></div>
    <input type="button" value="Add" />
</body>
</html>
查看更多
放荡不羁爱自由
6楼-- · 2019-01-16 23:25

Your html is invalid button is not a null tag. Try

<div id="Content">
   <button id="Add">Add</button>
</div> 
查看更多
Juvenile、少年°
7楼-- · 2019-01-16 23:39

we can do it in more easy way like by adding a function on button and on click we call that function for append.

<div id="Content">
<button id="Add" onclick="append();">Add Text</button>
</div> 
<script type="text/javascript">
function append()
{
$('<p>Text</p>').appendTo('#Content');
}
</script>
查看更多
登录 后发表回答