页面加载后删除div时的jQuery冲突 [英] jQuery conflict when removing div after page load

查看:99
本文介绍了页面加载后删除div时的jQuery冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从页面中删除一个div(最好完全阻止它加载) 但目前,我打算在页面加载后将其删除.

I'm trying to remove a div from the page (preferably prevent it from loading at all) but for now I'm settling on removing it after the page loads.

当我尝试以下代码行在jsFiddle 中时,#content div将如预期的那样删除了.

When I try the following lines of code in jsFiddle, the #content div gets removed, as expected.

<script type='text/javascript'>//<![CDATA[ 
  $(window).load(function(){
      $('#content').remove();
  });//]]>  
</script>

但是,我也曾尝试在一个实际的网站上实现它,但是在这种情况下,不会删除#content div.

However, I have also tried implementing it on an actual website, but in that case, the #content div isn't removed.

关于什么可能有问题的任何建议?

Any suggestions as to what might be wrong?

推荐答案

如果您要与使用美元进行操作的另一个库共享jQuery,则需要使用匿名包装程序来防止此类攻击:

If you're sharing jQuery with another library that uses the dollar for its operation you need to guard against it like this, using an anonymous wrapper:

(function($) {
    $(window).on('load', function(){
        $('#content').remove();
    });
}(jQuery));

请注意,我使用的是.on('load',fn)而不是.load().

您也可以将代码绑定到DOM上,而不是页面加载; jQuery将自身作为内部函数的第一个参数传递:

Instead of on page load you could also bind your code on DOM ready; jQuery passes itself as the first argument to the inner function:

jQuery(function($) {
    $('#content').remove();
});

这篇关于页面加载后删除div时的jQuery冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆