2014-01-21 106 views
0
document.getElementById('myButton').onclick = function() 
{  
    alert("button click"); 
    alert("bclick2"); 
    console.log("console log"); 
    alert("bclick3"); 
}; 

當我在tomcat服務器上的eclipse中運行這個時,會顯示前兩個對話框,但不是第三個,這讓我認爲它是console.log命令不工作。console.log導致代碼停止運行

可能是什麼問題?

+0

什麼瀏覽器?你也可以生成一個[jsFiddle](http://jsfiddle.net/)來重現它嗎? – Mgetz

+0

@Mgetz。呵呵。如果我使用IE8,它會顯示所有三個(還沒有計算出它在哪裏登錄)。 它在eclipse瀏覽器中運行時不會顯示第三個。 – dwjohnston

回答

2

你很可能會得到一個JavaScript錯誤,防止剩餘的代碼運行。 console對象僅在調試工具(如Firebug)存在時纔可用。爲了避免JavaScript錯誤時,它是不可用的,你可以通過這樣的檢查圍繞着它:

if (window.console && window.console.log) { 
    console.log("console log"); 
} 
+0

爲什麼downvote?這個答案在Internet Explorer中是正確的,在控制檯實際上已經打開之前,「console」沒有被定義。 –

+0

謝謝。我想我對console.log有什麼誤解 - 我以爲它是stdOut,但事實並非如此?爲了我的目的,只使用IE8而不是eclipse瀏覽器就行。 這裏的問題是相關的。 http://stackoverflow.com/questions/4539253/what-is-console-log?rq=1 – dwjohnston

0

對於更強大的解決方案,使用這段代碼(來自Twitter的源代碼所):

// Avoid `console` errors in browsers that lack a console. 
(function() { 
var method; 
var noop = function() {}; 
var methods = [ 
    'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 
    'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 
    'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 
    'timeStamp', 'trace', 'warn' 
]; 
var length = methods.length; 
var console = (window.console = window.console || {}); 

while (length--) { 
    method = methods[length]; 

    // Only stub undefined methods. 
    if (!console[method]) { 
     console[method] = noop; 
    } 
} 
}());