【问题标题】:document.getElementById() is returning null, despite being called inside $(document).ready [duplicate]document.getElementById() 正在返回 null,尽管在 $(document).ready 中被调用 [重复]
【发布时间】:2017-12-09 01:29:01
【问题描述】:

我正在为网页上的秒表开发圈数功能。这个想法是,每当您单击以记录一圈时,都会将当前时间附加到一个 div 中。但是,当我尝试引用 lapLog div 时,我从 getElementById 函数返回 null。我知道页面必须完全加载才能发现所有元素,这就是为什么我将按钮调用的函数放在 $(document).ready 块中,但尽管如此,它仍然返回 null。

相关JavaScript(timer.js):

$(document).ready(function(){
    $('#lapClkBtn').click(function(){
        // Only allow laps to be recorded if the timer is running
        if (ClkTimer.isAlive() == true) {
            var newEntry = ClkTimer.recordLap();
            lapLog = document.getElementById('lapLog');
            lapLog.innerHTML.append(newEntry);
            lapLog.animate({
                scrollTop: lapLog.prop('scrollHeight')
            }, 100);
        }
    });
})
    
function clkTimer(text, updateinterval) {
    this.recordLap = function() {
        this.lapNum = this.lapNum + 1;
        return String(this.lapNum) + "| " + this.formattedTime() + "<br>";
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="lapClkBtn">Lap</button>
<div class="lapLog"></div>

【问题讨论】:

  • 在控制台你可以看到ReferenceError: Can't find variable: ClkTimer你的函数是clkTimer

标签: javascript jquery html


【解决方案1】:

您的laplog 用作类。 getElementById 通过给定的 id 查找元素,而不是类。将其替换为id

<div id="lapLog"></div>

【讨论】:

  • 天啊!谢谢,我应该已经发现了。
  • 或使用getElementsByClass('lapLog')[0]...
  • 你是对的,但是对于一个元素,最好使用 id。
猜你喜欢
  • 2015-09-17
  • 2011-11-01
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多