为什么插入元素定义在外部和内部显示效果不一样,一个是最后一个p中添加一次就不再添加了,第二个是一直可以追加到p内部末尾
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-1.10.1.js"></script>
<script>
$(function () {
var $newNode = $('<b>ha</b>');
$('#btn01').click(function () {
$newNode.appendTo($('p'));
});
// $('#btn02').click(function () {
// var $newNode = $('<b>ha</b>');
// $newNode.appendTo($('p'));
// // $('p').append($newNode);
// });
});
</script>
</head>
<body>
<p>zww</p>
<p>xjw</p>
<p>123</p>
<button id="btn01">复制追加</button>
<button id="btn02">复制追加</button>
</body>
</html>
第一种:
第二种:
那当然了你第二种把var $newNode = $('<b>ha</b>');放到点击事件里了,就代表每次点击都新建了一个<b>ha</b>,运行多次。放到外面只创建一个。因为var $newNode = $('<b>ha</b>');只会运行一次