这个是可能的吗?
示例:
$('a.change').click(function(){
//code to change p tag to h5 tag
});
<p>Hello!</p>
<a id="change">change</a>因此,单击change锚点应该会导致<p>Hello!</p>部分更改为(举个例子) h5标记,这样在单击之后您就会得到<h5>Hello!</h5>。我知道您可以删除p标记并将其替换为h5,但是有必要修改HTML标记吗?
发布于 2009-05-28 01:33:33
一旦创建了dom元素,我相信标签就是不可变的。你必须这样做:
$(this).replaceWith($('<h5>' + this.innerHTML + '</h5>'));发布于 2013-12-09 19:49:19
这里有一个扩展,它将以尽可能多的方式在尽可能多的元素上完成所有任务……
示例用法:
保留现有类和属性:
$('div#change').replaceTag('<span>', true);
或
放弃现有的类和属性:
$('div#change').replaceTag('<span class=newclass>', false);
甚至是
用跨度替换所有div,复制类和属性,添加额外的类名
$('div').replaceTag($('<span>').addClass('wasDiv'), true);
插件来源:
$.extend({
replaceTag: function (currentElem, newTagObj, keepProps) {
var $currentElem = $(currentElem);
var i, $newTag = $(newTagObj).clone();
if (keepProps) {//{{{
newTag = $newTag[0];
newTag.className = currentElem.className;
$.extend(newTag.classList, currentElem.classList);
$.extend(newTag.attributes, currentElem.attributes);
}//}}}
$currentElem.wrapAll($newTag);
$currentElem.contents().unwrap();
// return node; (Error spotted by Frank van Luijn)
return this; // Suggested by ColeLawrence
}
});
$.fn.extend({
replaceTag: function (newTagObj, keepProps) {
// "return" suggested by ColeLawrence
return this.each(function() {
jQuery.replaceTag(this, newTagObj, keepProps);
});
}
});发布于 2009-05-28 01:38:06
您不应该更改标记的类型,而应该更改标记的样式(或者更确切地说,是具有特定id的标记)。更改文档的元素以应用样式更改不是一种好的做法。试试这个:
$('a.change').click(function() {
$('p#changed').css("font-weight", "bold");
});
<p id="changed">Hello!</p>
<a id="change">change</a>https://stackoverflow.com/questions/918792
复制相似问题