angularjs 使用javascript删除块HTML

byqmnocz  于 2023-04-04  发布在  Angular
关注(0)|答案(3)|浏览(142)

我在一个项目angularjs中使用owl-carousel,我尝试在$(element).data('owlCarousel').destroy();数据更改后重新初始化owl-carousel并删除此块:

<div class="owl-wrapper">
<div class="owl-item" ></div>
<div class="owl-item" ></div>
<div class="owl-item" ></div>
<div class="owl-item" ></div>
<div class="owl-item" ></div>
</div>

我试着这样做:

if(typeof $(element).data('owlCarousel') != 'undefined'){
                        $(element).data('owlCarousel').destroy();
                        $(element).find(".owl-item").removeClass("owl-item");                   
                    }

在页面加载它的工作正常,但对数据的变化,它不工作的例子,我有5个项目显示,然后我shoud得到5块<div class="owl-item" ></div>,但我得到我的5个项目预期和更多的空块。

c3frrgcw

c3frrgcw1#

你可以像这样删除整个元素:

const remove = el => el.parentElement.removeChild(el);

const owl = document.querySelector('div.owl-wrapper');

// remove it

remove(owl)

// check if it's removed (true = no such element in DOM) 

console.log(document.querySelector('div.owl-wrapper') === null)
<div class="owl-wrapper">
<div class="owl-item" >1</div>
<div class="owl-item" >2</div>
<div class="owl-item" >3</div>
<div class="owl-item" >4</div>
<div class="owl-item" >5</div>
</div>
yqkkidmi

yqkkidmi2#

你有没有试过

$(".owl-item").removeClass("owl-item");
rhfm7lfc

rhfm7lfc3#

使用jQuery**.remove()**方法:
$('div.owl-wrapper').remove();
参见https://api.jquery.com/remove/
基于@Egor解决方案的示例:

$('div.owl-wrapper').remove();

// check if it's removed (true = no such element in DOM) 

console.log(document.querySelector('div.owl-wrapper') === null)
<div class="owl-wrapper">
<div class="owl-item" >1</div>
<div class="owl-item" >2</div>
<div class="owl-item" >3</div>
<div class="owl-item" >4</div>
<div class="owl-item" >5</div>
</div>

相关问题