javascript - 프로토타입에 대해 질문이 있으신가요?
PHP中文网
PHP中文网 2017-05-19 10:24:13
0
2
458

프로토타입 체인을 이용하여 지방자치단체를 연결하는 방법을 작성합니다. 프로토타입 체인을 이용하여 확장할 수 있도록 초기 함수에 변수를 넣습니다. 초기화에는 문제가 없었지만 onchange를 사용하여 지방이나 도시를 선택할 때 문제가 발생했습니다. onchange.예, 분명히 AddressInit에서 초기화했지만 감지되지 않았습니다. 해결책을 알려주실 수 있나요?
코드:
//이것은 json의 짧은 부분입니다

으아아아

//이것은 HTML입니다

으아아아

//js입니다

으아아아
PHP中文网
PHP中文网

认证0级讲师

모든 응답(2)
左手右手慢动作

콜백 함수를 사용하려면 올바른 환경이 필요합니다.

이 줄을 넣어주세요

으아아아

로 변경되었습니다. 으아아아
滿天的星座

위에서 언급했듯이 이 포인터에는 문제가 있습니다.

this.selectProvince.onchange = this.changeProvince;this.selectProvince.onchange = this.changeProvince;

你的意思是指select的change事件的处理函数为 this.changeProvince, 即对其的一个引用。

实际也就是如下:

document.getElementById(selectProvince).onchange = function(){
    console.log(selectCity);
    this.selectCity.options.length = 0; // 触发时报错this.selectCity为undefined 因为this是dom元素
    this.selectCity.onchange = null; // 触发时报错this.selectCity为undefined
    if (this.selectProvince.selectedIndex == -1) return; // 触发时报错this.selectProvince为undefined 下面的this基本都有问题 事件处理函数中this为dom元素,而不是你的实例对象。
    var item = this.selectProvince.options[this.selectProvince.selectedIndex].obj;
    for (var i = 0; i < item.cityList.length; i++) {
        this.selectAddOption(this.selectCity, item.cityList[i].name, item.cityList[i]);
    }
    this.selected(this.selectCity, this.defaultCity);
    this.changeCity();
    this.selectCity.onchange = this.changeCity;
}

能看出问题了吗?事件处理函数中的this指的是dom对象,即document.getElementById(selectProvince) 它上面当然没有你需要的东西了。

可以如楼上所言的换为this.selectCity.onchange = this.changeCity.bind(this)

this.selectCity.onchange = this.changeCity; 这样写 只是表示selectCity.onchange 也是 this.changeCity这个函数,在js中,this的指向是实际运行时才决定,在onchange事件触发时,this.changeCity 函数内的this为dom元素,所以就出错了。bind方法可以替换函数内的this指向,生成一个新的函数。

this.changeCity.bind(this)这句在运行时,已经将this.changeCity函数内的this替换为了当前的this

select의 변경 이벤트 핸들러 함수가 이를 참조하는 this.changeProvince라는 뜻입니다. 🎜 🎜실제로는 다음과 같습니다. 🎜 으아아아 🎜문제가 보이나요? 이벤트 처리 함수의 this는 dom 개체, 즉 document.getElementById(selectProvince)를 참조합니다. 물론 여기에는 필요한 것이 없습니다. 🎜 🎜위에서 언급한 대로 this.selectCity.onchange = this.changeCity.bind(this)🎜로 변경할 수 있습니다. 🎜this.selectCity.onchange = this.changeCity; 이렇게 작성하면 selectCity.onchange가 js에서 this.changeCity 함수이기도 함을 의미합니다. 실제 런타임 onchange 이벤트가 발생했을 때 this.changeCity 함수의 this가 dom 요소인 것으로 판단되어 오류가 발생했습니다. bind 메소드는 함수 내의 this 포인터를 대체하고 새 함수를 생성할 수 있습니다. 🎜 🎜즉, this.changeCity.bind(this) 문장이 실행될 때 this.changeCity 함수의 this가 다음으로 대체되었습니다. 현재 this(this this는 인스턴스 개체를 나타냄)를 사용하여 필요한 효과를 얻습니다. 🎜
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!