Ale*_*ksi 0 html jquery copy hyperlink
我的HTML看起来像这样:
<div id="ProductCode"><span>Product number</span>2100022</div>
Run Code Online (Sandbox Code Playgroud)
使用jQuery,我想将代码更改为:
<div id="ProductCode"><span>Product number</span><a href=”http://www.site.com/2100022”>2100022</a></div>
Run Code Online (Sandbox Code Playgroud)
任何想法如何做到这一点?谢谢!
您可以迭代元素比较其Node.nodeType,如果节点是TEXT_NODE(3).然后使用.replaceWith()用anchor元素替换文本节点
$('#ProductCode').contents().each(function () {
if (this.nodeType == 3) {
var elem = $('<a>', {
href: "http://www.example.com/" + this.nodeValue,
text: this.nodeValue
});
$(this).replaceWith(elem);
}
});
Run Code Online (Sandbox Code Playgroud)
.wrap()是更好的选择
$('#ProductCode').contents().each(function () {
if (this.nodeType == 3) {
var elem = $('<a>', {
href: "http://www.example.com/" + this.nodeValue
});
$(this).wrap(elem);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1831 次 |
| 最近记录: |