使用jQuery更改HTML标记?这个是可能的吗?例子:$('a.change').click(function(){//code to change p tag to h5 tag});<p>Hello!</p><a id="change">change</a>因此,单击更改锚应该会导致<p>Hello!</p>部分更改为(例如)h5标记,以便以<h5>Hello!</h5>点击后。我知道您可以删除p标记并用h5替换它,但是是否有实际修改HTML标记的方法呢?
3 回答
当年话下
TA贡献1890条经验 获得超9个赞
保留现有的类和属性:
$('div#change').replaceTag('<span>', true);
丢弃现有类和属性:
$('div#change').replaceTag('<span class=newclass>', false);
将所有div替换为span、复制类和属性,添加额外的类名。
$('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); }); }});
- 3 回答
- 0 关注
- 456 浏览
添加回答
举报
0/150
提交
取消