• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

jquery 搞代码 4年前 (2021-12-27) 35次浏览 已收录 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 ht<p style="color:transparent">来源gao!daima.com搞$代!码网</p>ml>
<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>

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

以上就是如何使用jQuery将元素移动到另一个元素中?的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何使用jQuery将元素移动到另一个元素中?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址