2016-01-13 54 views
-3

这是功能。我包含来自Google CDN的Jquery库,它位于此脚本之前。 {

$(document).ready(function() { 

    function displayTime() { 
    var currentTime = new Date(); 
    var hours = currentTime.getHours(); 
    var minutes = currentTime.getMinutes(); 
    var seconds = currentTime.getSeconds(); 

    // This gets a "handle" to the clock div in our HTML 
    //This does not work??? 
    var clockDiv = $(document).getElementById('clock'); 
    //This works though 
    var clockDiv = document.getElementById('clock'); 

    // Then we set the text inside the clock div 
    // to the hours, minutes, and seconds of the current time 
    clockDiv.innerText = hours + ":" + minutes + ":" + seconds; 
    } 

    // This runs the displayTime function the first time 
    displayTime(); 

}); 

}

+5

因为jQuery没有getElementById方法...... ?????????? –

+0

$(document).'返回一个jQuery对象,其中'getElementById'是'document'对象的一个​​方法 –

+0

在jQuery中,您可以使用id选择器来获取对象'var clockDiv = $('#clock ');'then'clockDiv.text(hours +“:”+ minutes +“:”+ seconds);' –

回答

0

因为jQuery不同返回文档的信息。如果我没有记错它必须是:

$(document)[0].getElementById('clock'); 
+3

真的吗?为什么有人可能想这样做,使用'var clockDiv = $('#clock')[0];' –

+0

我不知道 - 我认为你的答案更好。 :-)但它确实回答了这个问题。 –

+0

声明*“jQuery不同地返回文档信息”*根本没有意义。 '$(document)[0]'仍然返回文档' – charlietfl

3

正如其他人所说,你将只使用Web API与jQuery的文档,你会改用选择来实现相同的功能。正如阿伦P激发态,你会做

var clockDiv = $('#clock'); // select the div with an ID of clock 
clockDiv.text(/* your text */); // set the text of the selected element to the passed argument 

jQuery是一个库摘要该Web API,以帮助跨浏览器的兼容性问题,并通常使导航和操作DOM更容易一点。

1
to set text in a div 

$('#clock').text('some text');