使用jQuery将元素移动到另一个元素中

13 篇文章 0 订阅
1 篇文章 0 订阅

想要使用jQuery将元素移动到另一个元素中,可以使用jQuery的内置方法append()或prepend()。下面本篇文章就来给大家介绍一下,希望对大家有所帮助。

方法1:使用append()方法

jQuery的append()方法用于在所选元素的末尾插入一些内容。

语法:

$(selector).append( content, function(index, html) )

参数:此方法接受上述两个参数

● content:它是必需参数,用于指定要在所选元素末尾插入的内容。content的可能值是HTML元素,jQuery对象和DOM元素。

● function(index,html):它是可选参数,用于指定将返回要插入的内容的函数。

  ● index:用于返回元素的索引位置。

  ● html:用于返回所选元素的当前HTML。

示例:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<style>
			#parent {
				height: 40px;
				width: 300px;
				background: green;
				padding: 10px;
				margin: 0 auto;
			}
			
			#child {
				height: 40px;
				width: 150px;
				margin: 0 auto;
				color: yellow;
			}
		</style>
	</head>

	<body style="text-align:center;">
		<div id="parent"></div>
		<br>
		<p id="child"> Hello World! Hello World!</p>
		<br>
		<button onclick="myGeeks()">移动</button>
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
		<script>
			function myGeeks() { 
	            $("#parent").append($("#child")); 
	        } 
		</script>
	</body>

</html>

效果图:

1.gif

方法2:使用prepend()方法

prepend()方法是jQuery中的内置方法,用于在所选元素的开头插入指定的内容。

语法:

$(selector).prepend(content, function)

参数:此方法接受上述两个参数

● content:需要参数,用于指定需要插入的内容。

● function:可选参数,用于指定调用后执行的函数。

示例:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<style>
			#parent {
				height: 40px;
				width: 300px;
				background: peru;
				padding: 10px;
				margin: 0 auto;
			}
			
			#child {
				height: 40px;
				width: 150px;
				margin: 0 auto;
				color: yellow;
			}
		</style>
	</head>

	<body style="text-align:center;">
		<div id="parent"></div>
		<br>
		<p id="child"> Hello World! Hello World!</p>
		<br>
		<button onclick="myGeeks()">移动</button>
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
		<script>
			function myGeeks() { 
	            $("#parent").prepend($("#child")); 
	        } 
		</script>
	</body>

</html>

效果图:

2.gif


本文参考地址:https://www.html.cn/qa/jquery/10418.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值