JS this關鍵字在ajax中使用出現問題解決方案
背景:
在一次web網站開發維護中,使用手機驗證碼進行登錄。再點擊獲取手機驗證碼時,驗證碼按鈕并沒有置灰,同時也沒有出現倒數讀秒的效果。
設置按鈕倒數60秒前端代碼:
var clock = ’’; var nums = 60; var btn; function sendCode(thisBtn) { btn = thisBtn; btn.disabled = true; //將按鈕置為不可點擊 btn.value = nums + ’秒重新獲取’; btn.className = ’regGetcodeBtn1’; if (clickNumber == 0) { clock = setInterval(doLoop, 1000); //一秒執行一次 } }
function doLoop() { nums--; if (nums > 0) { btn.value = nums + ’秒后重新獲取’; clickNumber = 1; } else { clearInterval(clock); //清除js定時器 btn.disabled = false; btn.value = ’獲取驗證碼’; btn.className = ’regGetcodeBtn1 color’; nums = 60; //重置時間 clickNumber = 0; } }
在向后端請求獲取短信驗證碼成功之后,調用sendCode()函數,實現如下效果:
但是在ajax請求,調用時,實際上該效果并沒有出現,代碼如下:
$.ajax({ url: servletUrl, type: 'post', dataType: ’JSON’, data: { name: name, securityCode: txtsecurityCode1/* strTelphone: strCodeTelphone, securityCode: txtsecurityCode1*/}, success: function (result) {//已經存在該名字提示用戶if (result.status == false) { console.log('傳入ajax中的this對象:' + this.location); $(’#hdVerifCode’).val(0); nums = 0; layer.alert(result.msg, { icon: 2 }); layer.close(loadingindex); // 刷新驗證碼 $(’#secImg’).click();} else { $(’#hdVerifCode’).val(1); sendCode(this); } },
這個時候,我i傳入一個this,原本意是代替觸發的btn對象,但是實際上,在傳入sendCode中時,卻并不是我所想的。查閱資料,學習了一下js中this這個關鍵字,好吧,在ajax的success中,this代替了傳入到看ajax的bbjcet對象,而不是觸發按鈕事件的btn了。所以,并沒有改變按鈕對象的狀態。
解決辦法:
A。在調用ajax方法之前,定義一個對象,接受this指代的對象。var that=this;然后在sendCode(that)傳入包裝好的this對象即可。
B。使用bind(this)關鍵字,綁定當前的this的事件對象。
總結 this關鍵字:
1。全局作用域和普通函數中,指向全局對象window;
console.log(this) //window //function聲明函數function bar () {console.log(this)}bar() //window //function聲明函數賦給變量var bar = function () {console.log(this)}bar() //window //自執行函數(function () {console.log(this)})(); //window
2。方法調用中,誰調用方法,this指向誰
//對象方法調用var person = { run: function () {console.log(this)}}person.run() // person//事件綁定var btn = document.querySelector('button')btn.onclick = function () { console.log(this) // btn}//事件監聽var btn = document.querySelector('button')btn.addEventListener(’click’, function () { console.log(this) //btn})//jqery中的ajax$.ajax(object)在ajax的succes中,this指向了傳入ajax的對象objsuccess:function(){ $(this).prevAll(’p’).css('text-decoration','line-through');}.bind(this)//使用bind(this)綁定當前this事件
3.在構造函數和構造函數原型中,this指向構造函數的實例。
//不使用new指向windowfunction Person(name) { console.log(this) // window this.name = name;}Person(’inwe’)//使用newvar people = new Person(’iwen’)function Person(name) { this.name = name console.log(this) //people self = this}console.log(self === people) //true//這里new改變了this指向,將this由window指向Person的實例對象people
4. 箭頭函數中指向外層作用域的 this
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: