JavaScript 이벤트 클릭을 트리거하려면 어떻게 해야 합니까?
페이지에 하이퍼링크가 있습니다.테스트 목적으로 하이퍼링크를 여러 번 클릭하는 것을 자동화하려고 합니다.JavaScript를 사용하여 하이퍼링크를 50번 클릭할 수 있는 방법이 있습니까?
<a href="#" target="_blank" onclick="javascript:Test("Test");">MSDN</a>
JavaScript에서 onClick 이벤트 트리거를 찾고 있습니다.
HTML 요소를 클릭 한 번 하기: 간단히 하기element.click()
대부분의 주요 브라우저가 이를 지원합니다.
클릭을 두 번 이상 반복하려면:요소에 ID를 추가하여 원하는 ID를 선택합니다.
<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>
에 전화합니다..click()
for 루프를 통해 JavaScript 코드의 메서드를 지정합니다.
var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
link.click();
갱신하다
이것은 오래된 대답이었다.요즘은 클릭만 하면 돼요.고급 이벤트 발생을 수행하려면 dispatchEvent를 사용합니다.
const body = document.body;
body.addEventListener('click', e => {
console.log('clicked body');
});
console.log('Using click()');
body.click();
console.log('Using dispatchEvent');
body.dispatchEvent(new Event('click'));
원답
사용하고 있는 것은, http://jsfiddle.net/mendesjuan/rHMCy/4/ 입니다.
IE9+와 연동하도록 업데이트됨
/**
* Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
* by testing for a 'synthetic=true' property on the event object
* @param {HTMLNode} node The node to fire the event handler on.
* @param {String} eventName The name of the event without the "on" (e.g., "focus")
*/
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style, you can drop this if you don't need to support IE8 and lower
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
콜링에 주의해 주세요.fireEvent(inputField, 'change');
입력 필드를 실제로 변경하는 것은 아닙니다.변경 이벤트를 실행하는 일반적인 사용 예는 프로그래밍 방식으로 필드를 설정하고 호출 후 이벤트핸들러를 호출하는 경우입니다.input.value="Something"
는 변경 이벤트를 트리거하지 않습니다.
뭐?
l.onclick();
does는 정확히 콜하고 있다.onclick
기능l
즉, 를 로 설정하고 있는 경우,l.onclick = myFunction;
설정되지 않은 경우l.onclick
, 아무것도 하지 않습니다.그에 반해서,
l.click();
클릭을 시뮬레이트하여 모든 이벤트핸들러를 기동합니다.l.addEventHandler('click', myFunction);
, HTML 또는 기타 방법으로 지정합니다.
정확하지 않거나 공개되지 않은 부분적 적용이 너무 많다는 것이 매우 부끄럽습니다.
가장 쉬운 방법은 콘솔을 사용하여 Chrome 또는 Opera를 사용하는 것입니다(예에서는 Chrome을 사용합니다).콘솔에 다음 코드를 입력합니다(일반적으로 1줄).
var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
l.click();
}
이렇게 하면 필요한 결과가 생성됩니다.
.click()
는 Android에서는 동작하지 않습니다(모바일 섹션의 Mozilla 문서를 참조).다음 방법으로 클릭 이벤트를 트리거할 수 있습니다.
function fireClick(node){
if (document.createEvent) {
var evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, false);
node.dispatchEvent(evt);
} else if (document.createEventObject) {
node.fireEvent('onclick') ;
} else if (typeof node.onclick == 'function') {
node.onclick();
}
}
이 투고부터
테스트 프레임워크 사용
이것은 도움이 될 수 있습니다.http://seleniumhq.org/ - Selenium은 웹 어플리케이션 자동 테스트 시스템입니다.
Firefox 플러그인 Selenium IDE를 사용하여 테스트를 생성할 수 있습니다.
이벤트 수동 실행
이벤트를 수동으로 올바른 방법으로 실행하려면 브라우저마다 다른 방법을 사용해야 합니다.el.dispatchEvent
또는el.fireEvent
어디에el
앵커 요소가 됩니다.둘 다 전달하려면 이벤트 개체를 구성해야 합니다.
완전히 올바르지는 않지만 빠르고 더러운 방법은 다음과 같습니다.
var el = document.getElementById('anchorelementid');
el.onclick(); // Not entirely correct because your event handler will be called
// without an Event object parameter.
IE9+
function triggerEvent(el, type){
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
}
사용 예:
var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');
출처 : https://plainjs.com/javascript/events/trigger-an-event-11/
버튼이 클릭되는 장소와 위치에 따라 트리거 기능을 호출하십시오.
<a href="#" id="myBtn" title="" >Button click </a>
function trigger(){
document.getElementById("myBtn").click();
}
적절한 경고:
element.onclick()
가 예상대로 동작하지 않습니다.내부 코드만 실행됩니다.onclick="" attribute
디폴트 동작은 트리거하지 않습니다.
있지 않은 만, 이 버튼은 켜지지 않았습니다.onclick
커스텀 기능은 정상적으로 실행되고 있었습니다.가가 had had had had had had had had had had had had 를 추가해야 했다.radio.checked = "true";
세팅할 수 있습니다. 다른이다.a.onclick()
있어야 한다window.location.href = "url";
)
언급URL : https://stackoverflow.com/questions/2381572/how-can-i-trigger-a-javascript-event-click
'programing' 카테고리의 다른 글
Javascript에서 배열에서 빈 요소 제거 (0) | 2023.01.15 |
---|---|
vuejs - 메서드를 통해 계산된 속성 변경 (0) | 2023.01.15 |
TextArea에서 줄 바꿈 (0) | 2023.01.15 |
원칙이 계산/생성된 열을 삭제하지 않도록 하는 방법 (0) | 2023.01.15 |
MySQL에서 인덱스 크기를 확인하는 방법 (0) | 2023.01.15 |