onclick 함수에서 'this'참조를 유지하면서 앵커 태그에서 onclick () 이벤트를 프로그래밍 방식으로 호출하려면 어떻게해야합니까?
다음은 작동하지 않습니다 ... (적어도 Firefox에서는 작동하지 않음 : document.getElementById('linkid').click()
기능이 아님)
<script type="text/javascript">
function doOnClick() {
document.getElementById('linkid').click();
//Should alert('/testlocation');
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
apply
해당 요소의 컨텍스트에서 이벤트 핸들러 가 필요합니다 .
var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
elem.onclick.apply(elem);
}
그렇지 않으면 this
위 코드가 실행되는 컨텍스트를 참조합니다.
이 문제를 해결하는 가장 좋은 방법은 Vanilla JS를 사용하는 것입니다.하지만 이미 jQuery를 사용하고 있다면 매우 쉬운 해결책이 있습니다.
<script type="text/javascript">
function doOnClick() {
$('#linkid').click();
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
IE8-10, Chrome, Firefox에서 테스트되었습니다.
이벤트를 트리거하려면 기본적으로 해당 요소에 대한 이벤트 핸들러를 호출하면됩니다. 코드에서 약간 변경하십시오.
var a = document.getElementById("element");
var evnt = a["onclick"];
if (typeof(evnt) == "function") {
evnt.call(a);
}
$("#linkid").trigger("click");
물론 OP는 이것이 작동하지 않는다고 매우 비슷하게 말했지만 나에게는 효과적이었습니다. 내 소스의 메모에 따르면 OP의 게시물 시간 또는 이후에 구현 된 것 같습니다. 아마도 이제 더 표준이 될 것입니다.
document.getElementsByName('MyElementsName')[0].click();
제 경우에는 버튼에 ID가 없었습니다. 요소에 ID가있는 경우 다음을 사용하는 것이 좋습니다.
document.getElementById('MyElementsId').click();
나는 원래이 방법을 시도했지만 작동하지 않았습니다. 인터넷 검색 후 다시 돌아와서 내 요소가 이름으로되어 있고 ID가 없다는 것을 깨달았습니다. 올바른 속성을 호출하고 있는지 다시 확인하십시오.
출처 : https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
handleEvent 메소드 https://developer.mozilla.org/en-US/docs/Web/API/EventListener를 살펴보십시오.
"원시"자바 스크립트 :
function MyObj() {
this.abc = "ABC";
}
MyObj.prototype.handleEvent = function(e) {
console.log("caught event: "+e.type);
console.log(this.abc);
}
var myObj = new MyObj();
document.querySelector("#myElement").addEventListener('click', myObj);
이제 요소 (id "myElement"포함)를 클릭하면 콘솔에 다음이 인쇄됩니다.
잡힌 이벤트 : 클릭
ABC
이를 통해 개체 메서드를 이벤트 핸들러로 사용할 수 있으며 해당 메서드의 모든 개체 속성에 액세스 할 수 있습니다.
당신은 할 수 없습니다 (즉, 같은 : 그냥 직접 또는 addEventListener에 객체의 메서드를 전달 element.addEventListener('click',myObj.myMethod);
) 및 기대 myMethod
나는 일반적으로 객체에서 호출 된 것처럼 행동 할 수 있습니다. addEventListener에 전달 된 모든 함수가 참조되는 대신 복사되었다고 생각합니다. 예를 들어, 이벤트 리스너 함수 참조를 addEventListener (변수 형식)에 전달한 다음이 참조를 설정 해제하면 이벤트가 포착 될 때 이벤트 리스너가 계속 실행됩니다.
Another (less elegant) workaround to pass a method as event listener and stil this
and still have access to object properties within the event listener would be something like that:
// see above for definition of MyObj
var myObj = new MyObj();
document.querySelector("#myElement").addEventListener('click', myObj.handleEvent.bind(myObj));
If you're using this purely to reference the function in the onclick attribute, this seems like a very bad idea. Inline events are a bad idea in general.
I would suggest the following:
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
handler = function(){
showHref(el);
}
showHref = function(el) {
alert(el.href);
}
var el = document.getElementById('linkid');
addEvent(el, 'click', handler);
If you want to call the same function from other javascript code, simulating a click to call the function is not the best way. Consider:
function doOnClick() {
showHref(document.getElementById('linkid'));
}
Old thread, but the question is still relevant, so...
(1) The example in your question now DOES work in Firefox. However in addition to calling the event handler (which displays an alert), it ALSO clicks on the link, causing navigation (once the alert is dismissed).
(2) To JUST call the event handler (without triggering navigation) merely replace:
document.getElementById('linkid').click();
with
document.getElementById('linkid').onclick();
In general I would recommend against calling the event handlers 'manually'.
- It's unclear what gets executed because of multiple registered listeners
- Danger to get into a recursive and infinite event-loop (click A triggering Click B, triggering click A, etc.)
- Redundant updates to the DOM
- Hard to distinguish actual changes in the view caused by the user from changes made as initialisation code (which should be run only once).
Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.
'code' 카테고리의 다른 글
Git 흐름-다른 기능 분기에서 기능 분기 만들기 (0) | 2020.10.12 |
---|---|
도커 실행이 프로그래밍 방식으로 성공했는지 감지하는 방법은 무엇입니까? (0) | 2020.10.12 |
WAMPServer의 Windows 명령 줄에서 PHP를 실행하는 방법 (0) | 2020.10.12 |
Angularjs 단순 파일 다운로드로 인해 라우터가 리디렉션 됨 (0) | 2020.10.12 |
requests.get ()이 반환되지 않는 이유는 무엇입니까? (0) | 2020.10.12 |