jQuery用另一个保存数据替换标签



我有这个 <p> tag

<p class='form-control' data-color='inherit' data-width='12' data-type='sh_info' name='shortcode[]' data-style=''>Some dynamic text</p>

我想要,on clicktextarea标签替换它,但我希望所有数据和类都持续存在。我在jQuery

中添加此功能
$( "p.form-control" ).click(function() {
  $( this ).replaceWith( "<textarea>" + $( this ).text() + "</textarea>" );
});

但是我想知道是否有一个函数可以让您仅用其他功能代替标签?

您可以使用以下方式:

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");
});

最新更新