清除DOM元素错误 [英] Remove DOM Element Error

查看:65
本文介绍了清除DOM元素错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码,我需要删除生成的新元素.它不起作用. Firebug中没有出现JS错误.

Using this code, I need to remove the generated new element. It is not working. No JS errors are appearing in firebug.

$('.popular-list li a').live("click",function() //this will apply to all anchor tags
            { 
                    var stuff = $(this).text();
                            var hasDuplicate = false;

          $('#favoritesdrinks li').each( function(){
           if ($(this).text() === stuff ){
              hasDuplicate = true;
              return false;
           }
        });

        if (hasDuplicate ) {
           alert("Already Added") } 
        else {         
           $('#favoritesdrinks').append('<li>'+stuff+' --- <a href="javascript:;" class="remove">Remove Item </a> </li>'); 
        }
    });

Removal:

  $("a.remove").click(function() {
    $(this).fadeOut(500, function() { $(this).remove(); });
    });

推荐答案

您需要对带有remove类的锚使用.live事件.同样,此上下文将是锚点单击内的锚点,因此您需要使用.parent()来淡出&删除li

You need to use the .live event for the anchors with class remove. Also the context of this will be the anchor inside the anchor click therefore you need to use .parent() to fadeOut & remove the li

$('.popular-list li a').live("click",function()  { 
   var stuff = $(this).text();
   var hasDuplicate = false;

   $('#favoritesdrinks li').each( function(){
      if ($(this).text() === stuff ){
          hasDuplicate = true;
          return false;
      }
   });

   if (hasDuplicate ) {
      alert("Already Added") } 
   else {         
      $('#favoritesdrinks').append('<li>'+stuff+' --- <a href="#" class="remove">Remove Item </a> </li>'); 
    }

  });

  $("a.remove").live('click', function(ev) {
    ev.preventDefault();
    $(this).parent().fadeOut(500, function(ev) { 
        $(this).remove(); 
    });
  });

这篇关于清除DOM元素错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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