jQuery 有个 wrap
函数,可以使用指定的 HTML 元素来包裹每个被选元素。
比如下面这段 HTML:
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
我们使用 wrap
函数给 class
为 inner
的元素加上 class
为 new
的 div:
$( ".inner" ).wrap( "<div class='new'></div>" );
结果为:
<div class="container">
<div class="new">
<div class="inner">Hello</div>
</div>
<div class="new">
<div class="inner">Goodbye</div>
</div>
</div>
wrap
函数也支持回调函数作为参数:
$( ".inner" ).wrap(function() {
return "<div class='" + $( this ).text() + "'></div>";
});
结果为:
<div class="container">
<div class="Hello">
<div class="inner">Hello</div>
</div>
<div class="Goodbye">
<div class="inner">Goodbye</div>
</div>
</div>
jQuery 的 wrap
函数非常好用,所以我在 PHP 中也简单实现相应的版本:
function wpjam_wrap($text, $wrap){
$pos = strpos($wrap, '></');
if($pos !== false){
return substr_replace($wrap, '>'.$text.'</', $pos, 3);
}elseif(is_callable($wrap)){
return call_user_func_array($wrap, $text);
}
return $text;
}
该功能已经整合到 WPJAM Basic 插件中,并已免费提供下载,简单勾选或者设置下即可开启!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有