[英]Cross-origin object when everything is coming from localhost
每次用戶更改我網頁上的文本輸入時,我都在嘗試進行記錄。 我正在使用以下內容:
function formInit(socketObject) {
$('input:text').change( (eventObject) => {
console.log(document.domain);
console.log(JSON.stringify($(this)));
//... send stuff via socketObject
});
}
我從$(document).ready()
調用。 我在第四行收到以下錯誤,即記錄 $(this) 的那一行:
SecurityError:權限被拒絕訪問跨域對象上的屬性“toJSON”
盡管console.log(document.domain);
從腳本和從它被調用的主文檔中返回localhost
。 本地主機上的燒瓶服務器唯一沒有提供的是幾個庫(jquery、socketio、cleave)以及散景圖中的一些組件,我很確定它們不符合input:text
,當然不是我在調試中 .change() 的事情。
誰能建議我在這里哪里出錯了,或者我應該去哪里找? 謝謝。
錯誤是因為this
不是您似乎期望的input:text
元素,因為您使用的是箭頭函數,因此未維護詞法范圍。 您要么需要將箭頭函數更改為匿名函數:
function formInit(socketObject) {
$('input:text').change(function() {
// 'this' now refers to the element which raised the event
});
}
或者保留箭頭函數,但從引發並作為參數提供給處理函數的事件中獲取對元素的引用:
function formInit(socketObject) {
$('input:text').change(e => {
// 'e.target' now refers to the element which raised the event
});
}
除了錯誤之外,字符串化整個 jQuery 對象有點奇怪。 最好只提取您需要的相關屬性,如下所示:
function formInit(socketObject) {
$('input:text').change((e) => {
console.log(document.domain);
console.log({
id: e.target.id,
value: e.target.value
// other properies here...
});
// send stuff via socketObject...
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.