我有<p>
标记
<p class='form-control' data-color='inherit' data-width='12' data-type='sh_info' name='shortcode[]' data-style=''>Some dynamic text</p>
我希望,on click
将其替换为textarea
标记,但我希望我的所有数据和类都能保留。我在jquery
$( "p.form-control" ).click(function() {
$( this ).replaceWith( "<textarea>" + $( this ).text() + "</textarea>" );
});
但是我想知道是否有一个函数允许你用其他东西替换标签?
答案 0 :(得分:0)
您可以使用:
function ReplaceElement(elementToReplace, currentType, newType) {
// Convert the elementToReplace into its string representation
var tmp = document.createElement("div"); // Create div to wrap the elementToReplace in
tmp.appendChild($(elementToReplace).clone()[0]); // Clone the elementToReplace and add it to the container tmp element
// Replace the current tags with the new tags and insert after the elementToReplace
$(tmp.innerHTML.replace("<" + currentType, "<" + newType).replace("/" + currentType + ">", "/" + newType + ">")).insertAfter(elementToReplace);
$(elementToReplace).remove(); // Remove the old element from the DOM
}
像这样:
$( "p" ).click(function() {
ReplaceElement(this, "p", "textarea");
});