jQuery如何用新HTML元素替换所选元素?

在jQuery中可以使用replaceAll()方法来用新HTML元素替换所选元素;该方法是jQuery中的一个内置方法,用于把被选元素替换为新的 HTML 元素。下面本篇文章就来给大家介绍一下jQuery的replaceAll()方法,希望对大家有所帮助。

replaceAll()方法用于用新的HTML元素替换所选元素。

语法:

$(content).replaceAll(selector)

参数:

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

● selector:指定要替换的元素的必需参数。

返回值:此方法返回具有新内容的所选元素。

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<style>
			div { 
                width: 60%; 
                height: 150px; 
                padding: 10px; 
                border: 2px solid #000; 
                font-size: 20px; 
                text-align:center; 
            } 
            p { 
                font-size:25px; 
                font-weight:bold; 
            }
		</style>
	</head>
	<body>
		<div> 
            <p>Welcome to here!</p> 
            <button>单击</button> 
            <br> 
        </div>
		<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
		<script> 
            $(document).ready(function() { 
                $("button").click(function() { 
                    $("<h1>Hello!</h1>").replaceAll("p"); 
                    $("h1").css({"color":"red"}); 
                    $("div").css({"border":"2px solid red"}); 
                }); 
            }); 
        </script> 
	</body>

</html>

效果图:

2.gif

以上就是jQuery如何用新HTML元素替换所选元素?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » jQuery 答疑