그래서 내 HTML에서는 버튼의 onclick 함수를 실행하고 있습니다. 그런 다음 클릭 한 요소의 형제 값을 innerHTML;
얻고 싶습니다. 그러나 오래된 'undefined is not object error'가 나타납니다.JS - 'this'와 nextSibling - undefined는 객체가 아닙니다
<button onclick="helloWorld();">
Click Me
</button>
<p>
Hello
</p>
그리고 내 자바 스크립트 :
<script>
function helloWorld() {
var justClicked = this;
var sibling = justClicked.nextSibling.textContent;
alert(sibling);
}
</script>
어떤 생각이 내 HTML 구조인가?
'this'는 당신이 생각하는 것과 다릅니다. 핸들러 속성에서 전달해야합니다. – SLaks
어떻게하면됩니까? – dwinnbrown
'foo()'와 같은 함수를 호출하면,'this'는 전역 객체 또는'strict' 모드에서'undefined'를 참조합니다. –