<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="test">
<p>hello,你好!</p>
</div>
<script>
var outerHTML=$(".test").prop("outerHTML");
console.log(outerHTML);//結果:<div class="test"><p>hello,你好!</p></div>
</script>
</body>
</html>
在研究外協代碼的時候,發現很多這一行代碼: return domEle.prop('outerHTML');
prop() 方法:
當該方法用於返回屬性值時,則返回第一個匹配元素的值。
當該方法用於設置屬性值時,則爲匹配元素集合設置一個或多個屬性/值對。
注意:prop() 方法應該用於檢索屬性值,例如 DOM 屬性(如 selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected)。
提示:如需檢索 HTML 屬性,請使用 attr() 方法代替。如需移除屬性,請使用 removeProp() 方法。
語法:
返回屬性的值:$(selector).prop(property)
設置屬性和值:$(selector).prop(property,value)
使用函數設置屬性和值:$(selector).prop(property,function(index,currentvalue))
設置多個屬性和值:$(selector).prop({property:value, property:value,...})
參數 | 描述 |
---|---|
property | 規定屬性的名稱。 |
value | 規定屬性的值。 |
function(index,currentvalue) | 規定返回要設置的屬性值的函數。
|
jQuery.prop("outerHTML"):獲取包含自身在內的HTML元素的HTML代碼
(區別:jQuery.html() 是獲取當前節點下的html代碼)
一、jquery獲取outerhtml
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="test">
<p>hello,你好!</p>
</div>
<script>
//下面這個打印可以看出outerHTML是什麼東西
var outerHTML=$(".test").prop("outerHTML");
console.log(outerHTML);//結果:<div class="test"><p>hello,你好!</p></div>
</script>
</body>
二、jquery設置outerhtml
$('.test').prop('outerHTML', '<input>');