使用 detach 和 prepend 将子元素从 DIV (h4) 内移动到它的父 DIV(树上的两个 DIV)。我的代码正在工作,但它需要页面上此 DIV 的每个实例,并将页面上的所有多个 DIV 添加到每个父 DIV 的顶部。
jQuery( function($){
$('.mp_m_blurb_1 h4.et_pb_module_header').detach().prependTo('.mp_m_blurb_1 .et_pb_blurb_content');
});
我意识到在具有相同 ID/类的多个 DIV 元素的页面上,这就是将要发生的事情。那么我如何告诉子元素移动到另一个父 DIV,但仅相对于其父元素,而不必手动为每个元素添加唯一 ID。
在某些页面上可能有 10-15 个以上的这些父 DIV,我不想为每个页面添加一个唯一的 ID,然后更新我的 jQuery。
我希望能够使用一个类。有没有更好的方法或方法?
尝试了这些资源,但没有帮助
https://www.elated.com/jquery-removing-replacing-moving-elements/
下面是有效的代码,但正如您所看到的,这将变得冗长乏味。;-)
jQuery( function($){
$('#mp_blurb_0 h4.et_pb_module_header').detach().prependTo('#mp_blurb_0 .et_pb_blurb_content');
$('#mp_blurb_1 h4.et_pb_module_header').detach().prependTo('#mp_blurb_1 .et_pb_blurb_content');
$('#mp_blurb_2 h4.et_pb_module_header').detach().prependTo('#mp_blurb_2 .et_pb_blurb_content');
$('#mp_blurb_3 h4.et_pb_module_header').detach().prependTo('#mp_blurb_3 .et_pb_blurb_content');
$('#mp_blurb_4 h4.et_pb_module_header').detach().prependTo('#mp_blurb_4 .et_pb_blurb_content');
$('#mp_blurb_5 h4.et_pb_module_header').detach().prependTo('#mp_blurb_5 .et_pb_blurb_content');
});
您可以结合使用jQuery 的.each()
方法和以选择器开头的属性。
使用$('[id^="mp_blurb_"]')
将选择 ID 以 开头的所有元素mp_blurp_
。
$('[id^="mp_blurb_"]').each(function() {
var $this = $(this);
var $content = $this.find('.et_pb_blurb_content');
$this.find('h4.et_pb_module_header').detach().prependTo( $content );
});
在此处查看我的工作示例:https : //jsfiddle.net/z8of7qxp/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句