从html中删除选定的类

时间:2012-09-20 16:39:10

标签: jquery html removeclass

我想用jQuery加载html代码并从这段代码中删除一些类,我的代码是:

<!DOCTYPE html>
<html>
   <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>
      <div id="new-nav"></div>
      <script>
         $("#new-nav").load("/php/grab.php");

      </script>
      <script>
         $('.main_title_news_submain_block').remove();
      </script>
   </body>
</html>

问题是.remove功能不起作用,我不知道为什么?

4 个答案:

答案 0 :(得分:3)

将其包裹在document.ready内如果该html元素在页面加载后。

$(function () {
   $('.main_title_news_submain_block').remove();
});

如果使用.load加载,则将其添加到回调中。

$("#new-nav").load("/php/grab.php", function () {
   $('.main_title_news_submain_block').remove();
});

答案 1 :(得分:2)

您是否对load方法的回调进行了尝试?

  $(function(){
      $("#new-nav").load("/php/grab.php",function(){ 
         $('.main_title_news_submain_block').remove();              
      });
  });
  

如果提供“完整”回调,则在之后执行   已经执行了后处理和HTML插入。

因此,在load函数将内容加载到DOM中的指定div之后,将执行带有remove()方法的行。

答案 2 :(得分:2)

您需要在使用回调函数加载内容后执行.remove()

$("#new-nav").load("/php/grab.php", function(){
    /*removes the element with class main_title_news_submain_block*/
    $('.main_title_news_submain_block').remove();
});

编辑: 您也可以将文档中的所有内容都包装好,以确保在dom中加载id为new-nav的元素后发生加载。

$(document).ready(function(){
    $("#new-nav").load("/php/grab.php", function(){
        /*removes the element with class main_title_news_submain_block*/
        $('.main_title_news_submain_block').remove(); 
    });
});

答案 3 :(得分:1)

我发现你没有在任何地方使用DOM就绪功能。确保你在那里写下你的脚本,这样就不会发现任何异常。

<script type="text/javascript">
  $(function() {
      $("#new-nav").load("/php/grab.php" , function() {
           $('.main_title_news_submain_block').remove(); 
       });
   });
</script>