例如,如果我使用此代碼:$('#iddoesnotexist').remove();
如果此ID不在頁面中,我將不會收到錯誤,如何使顯示錯誤?如何在jQuery中調試最簡單的方法?
默認情況下選擇該行爲,否則會jQuery的定期扔NullReference
例外,但是這是我期待的...
例如,如果我使用此代碼:$('#iddoesnotexist').remove();
如果此ID不在頁面中,我將不會收到錯誤,如何使顯示錯誤?如何在jQuery中調試最簡單的方法?
默認情況下選擇該行爲,否則會jQuery的定期扔NullReference
例外,但是這是我期待的...
您可以創建自己的jQuery的擴展,我想。我想*把它寫成一個斷言:
$.fn.mustExist = function() {
if(!this.length) {
throw new Error("Collection was empty.");
}
return this;
};
發育過程:
$('#iddoesnotexist').mustExist().remove();
*其實,我不會使用jQuery; document.getElementById
也保護你從這樣的事情;)
參見:
jQuery Debugging 和 http://jqueryfordesigners.com/debugging-tools/ 和 http://www.jquery4u.com/utilities/live-jquery-debugging-firebug/ 和 http://samdutton.wordpress.com/2010/09/16/jquery-debugging-tips/ 和 http://trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug/
jQuery的調試文章。而且,正如評論中所述,最簡單的調試方式是使用console.log
。
如果要將此行爲默認爲所有DOM選擇,則可以爲jQuery
函數創建包裝函數。
var my_$ = function(selector) {
var result = jQuery.apply(this, arguments);
if (typeof selector === "string" && !result.length)
throw new Error("No matches found");
return result;
};
my_$("#foobar"); // No matches found
一定要使用自己的參考,而不是覆蓋jQuery
或$
標識符。
我使用console.log進行調試:) – Ignas
您可以使用'console.log'或在devtools中設置斷點,或者使用firequery,多個選項,如您所見 – elclanrs
我認爲標題是一個不錯的選擇。據我瞭解,你尋找一個選項,使jQuery在空匹配時拋出錯誤,但很多人只是看標題和推薦調試工具... – madth3