【问题标题】:removing an appended element using javascript/closure?使用 javascript/closure 删除附加元素?
【发布时间】:2012-02-28 15:59:01
【问题描述】:

I currently have a click event in place that when selected appends a search box to .header, this is done using google closure.我现在的问题是,如果我单击关闭按钮,我想删除这个附加元素。我知道使用 jQuery 只需要 .remove() 但我不确定如何在闭包或 vanilla js 中实现这一点。谁能建议我如何做到这一点?

当前代码:

if(goog.dom.getElementsByClass('pe')){
    var searchCtn = goog.dom.getElementsByClass('search');     
    var headerWrapper = goog.dom.getElementByClass('header');     
    goog.dom.append(headerWrapper,searchCtn); 
} 

var closeButton = goog.dom.getElement('close');
    goog.events.listen(closeButton, goog.events.EventType.CLICK, function() {
    console.log('Remove appended');
}, false, this); 

【问题讨论】:

    标签: javascript google-closure google-closure-library


    【解决方案1】:

    函数是这样的:

    goog.dom.removeNode = function(node) {
      return node && node.parentNode ? node.parentNode.removeChild(node) : null;
    };
    

    所以代码如下(假设搜索框是关闭按钮的父级):

    goog.events.listen(closeButton, goog.events.EventType.CLICK, function() {
        goog.dom.removeNode(this.parentNode);
    }, false, this); 
    

    【讨论】:

    • 感谢回复,this.parentNode 以关闭按钮的父级为目标,对吗?如果附加元素不是关闭按钮父级,我如何定位附加元素?
    • @styler 所以goog.dom.removeNode(searchCtn);
    【解决方案2】:

    只需使用element.removeChild(y)

    $(function() {
      $('span').click(function() {    
        this.parentNode.removeChild(this);
      });
    });
    

    那是 jquery,但很容易转换为普通的旧 javascript 或您所在的任何框架。

    【讨论】:

      猜你喜欢
      • 2014-07-10
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2010-12-11
      • 2014-12-25
      • 2011-08-21
      • 2010-09-05
      相关资源
      最近更新 更多