【问题标题】:Uncaught TypeError: Cannot read property 'scrollHeight' of undefined未捕获的类型错误:无法读取未定义的属性“scrollHeight”
【发布时间】:2014-03-29 15:31:09
【问题描述】:

为什么会出现这个错误:

未捕获的类型错误:无法读取未定义的属性“scrollHeight”。

“阅读更多”按钮将我返回到页面顶部,而不是更改我的 <div> 元素的高度。我该如何解决这个问题?

这是我的代码:

function piki( $atts, $content = null ) {
{ ?>
<script type="text/javascript">
var h = jQuery('#piki')[0].scrollHeight;


jQuery('#more').click(function(e) {
    e.stopPropagation();
    jQuery('#piki').animate({
        'height': h
    })
});

jQuery(document).click(function() {
    jQuery('#piki').animate({
        'height': '50px'
    })
})
</script>
<?php }
    $url = '/?s=';
    $str = '';

    $output = array();
    $count = 0;

    foreach (explode(", ",$content) as $content) {
        $count++;
        $output[] = "<a href='" . $url . $content . "'>" . $content . "</a>";
        if ($count == 50) {
            break;
        }
    }

    return '<div id="piki" class="piki">'.implode(", ", $output).'</div><a id="more" style="float: left;" href="#">Read more</a>';
}
add_shortcode( 'piki', 'piki' );

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    问题是jQuery('#piki')[0] 没有选择任何元素。因此,当您尝试获取scrollHeight 时,您是在尝试从undefined 值中获取一个字段。这是因为&lt;script&gt; 中的代码在浏览器处理&lt;div id="piki"... 元素之前执行。如果您将&lt;script&gt; 移动到它出现并在div 之后执行,那么JavaScript 应该可以正确执行。

    【讨论】:

    • 我认为这是一个很好的答案,并为我工作。谢谢路易斯。
    【解决方案2】:

    在调用事件处理程序之前始终检查元素是否存在是一种很好的做法。

    if ( document.getElementById('#piko') ) {
      //call some event handlers on #piko
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 1970-01-01
      • 2021-12-22
      • 2015-01-06
      • 2017-07-26
      • 2019-02-26
      • 2021-12-25
      相关资源
      最近更新 更多