【问题标题】:jQuery appendTo Parent TroublejQuery appendTo 父问题
【发布时间】:2015-12-12 04:16:34
【问题描述】:

首先,感谢您提前提供的帮助。

我试图基本上在我在页面上找到的每个锚标记上方放置一个悬停的div。所以我得到偏移量,找到每个元素的高度和宽度,然后创建一个新的 div 并将 CSS 设置为这些测量值。我在将新创建的 DIV 附加到锚标记的父级的代码时遇到问题。

$( "a" ).each(function( index ) {
    tempoffset = $( this ).offset();
    tempheight = $( this ).height();
    tempwidth = $( this ).width();
    tempoverlay = document.createElement('div');
    tempoverlay.appendTo($(this).parent());
    tempoverlay.setAttribute("style","background: #ccc; position: fixed; height: " + tempheight + "px; width: " + tempwidth + "px; left: " + tempoffset.left + "px; top: " + tempoffset.top + "px;");
});

我收到错误提示

tempoverlay.appendTo 不是函数 对这里可能发生的事情有什么想法吗?

【问题讨论】:

    标签: javascript jquery appendto


    【解决方案1】:

    tempoverlay 是原生 DOM 节点,而不是 jQuery 对象,因为这是 document.createElement 创建的,因此它没有 appendTo 方法。

    改为创建 jQuery 对象

    var tempoverlay = $('<div />');
    
    tempoverlay.appendTo( $(this).parent() )
               .css({
                       background : '#ccc',
                       position   : 'fixed',
                       height     : tempheigh,
                       width      : tempwidth,
                       left       : tempoffset.left,
                       top        : tempoffset.top
                   });
    

    【讨论】:

      【解决方案2】:

      尝试使用append(),因为tempoverlay不是jquery对象,你不能在dom节点上调用jquery函数.appendTo

      $( "a" ).each(function( index ) {
           tempoffset = $( this ).offset();
           tempheight = $( this ).height();
           tempwidth = $( this ).width();
           tempoverlay = document.createElement('div');
           tempoverlay.setAttribute("style","background: #ccc; position: fixed; height: " + tempheight + "px; width: " + tempwidth + "px; left: " + tempoffset.left + "px; top: " + tempoffset.top + "px;");
      
           $(this).parent().append(tempoverlay);
      });
      

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        tempoverlay 不是 jQuery 元素。这是一个dom元素。

        试试这个:$(tempoverlay).appendTo...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-29
          • 2018-05-19
          • 2015-07-02
          • 1970-01-01
          • 2014-01-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多