所以我想在一個ajax成功函式中使用來自外部函式的this。我試圖應用這些解決方案,但不知何故,我無法使其發揮作用。
// Submit vote on submit。
$('.vote-cho-div').on('click', function(event){
event.preventDefault()。
//系結被點擊的物件。
this.submit_vote。 bind(this); // so I have to bind the element to use it in the ajax function?
//Fire ajax
submit_vote(this.id, this) 。
});
// AJAX for posting
function submit_vote(vote) {
$.ajax({
url : "submit-vote/"。
headers: {'X-CSRFToken'/span>: csrftoken},
型別: "POST"。
資料。{ vote : vote },
success : function(data) {
if(data.status === 1) {
console.log(this) //無法訪問初始點擊的元素。
}
未發現的型別錯誤。不能讀取未定義的屬性(讀取'bind')
uj5u.com熱心網友回復:
你有兩個問題(和一個無意義的爭論)。
submit_vote是一個全域,而不是一個元素的屬性。要訪問它,你不需要使用this。bind回傳一個新函式。它不會突變現有的函式bind回傳一個新的函式。submit_vote只接受一個引數 。
你有兩個問題(和無意義的爭論)。
所以:
const localSubmitVote = submit_vote.bind(this)。
localSubmitVote(this.id)。
然而......bind只有在你打算存盤一個函式時才有用,這樣你就可以把它傳遞出去或多次使用它。
你沒有這樣做,你只是呼叫它一次,所以使用call
submit_vote. call(this, this.id) 。
然而...submit_vote并不是一個方法。首先,把它設計成使用this是不明智的。因此,更好的方法是重新設計它,只使用你之前傳遞的第二個引數。
function submit_vote(vote, element) {
$.ajax({
/ ...
success: function(data) {
if (data.status == 1) {
console.log(element)。
}
}
});
}
而且
submit_vote(this.id,this)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/323829.html
標籤:
