2017-11-08 18 views
1

?입력 유형 = 'file'이 (가) 이벤트를 전달하지 않는 이유는 무엇입니까? 이 간단한 예제가 작동하지 않는 이유는

<input id="image" type="file"/> 
<img src='https://cdn.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png' onclick='imageLoad()'></img> 
<script> 
    function imageLoad() {  
    let ev = new Event('click', {bubbles: true}); 
    image.dispatchEvent(ev); 
    } 
</script> 
+0

"작동하지 않음"을 정의하십시오. 'image'는 정의되어 있지 않습니다. 콘솔이 아마 –

+0

을 말하고있을 것입니다. 또한'img'는 [* void element *] (https://www.w3.org/TR/html5/syntax.html#void-elements)입니다.), 절대로 닫는 태그가 없습니다. ''을 쓰지 마십시오. HTML에서는 단지 ''입니다. XHTML에서 (아마 사용하지 않을 것입니다), 그것은 ''입니다. –

+0

@JeremyThille : 안타깝게도,'image'는 정의되어 있지 않습니다.'id'가 있기 때문에 파일 입력을위한 자동 전역입니다. : - | –

답변

0

첫째, <img> 가까운 태그를 확인합니다. 둘째, 브라우저의 보안 원칙 때문에 js를 통해 입력의 클릭 이벤트를 전달할 수 없습니다. 사업부를 들어, 확인 될 것입니다 :

function imageLoad() { 
 
    let image = document.querySelector('#div'); 
 
    let ev = new Event('click', {bubbles: true}); 
 
    image.dispatchEvent(ev); 
 
    } 
 
    
 
function clickDiv(){ 
 
    console.log('clicked the div'); 
 
}
<input id="image" type="file" /> 
 
<div id="div" onclick="clickDiv()">123</div> 
 
<img src='https://cdn.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png' onclick='imageLoad()' />

0

특정 보안 관련 사항이 적용하는 것이 정확하지만, 당신이 MouseEventEvent 생성자를 변경하면 목표에 따라이 예에서 작동합니다 .

... 
<body> 
<input id="image" type="file" /> 
<img id="handle" src="https://cdn.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png" /> 
<script> 
    let handle = document.getElementById('handle'); 
    handle.addEventListener('click', imageLoad, false); 

    function imageLoad() { 
    let ev = new MouseEvent('click', {bubbles: true}); 
    image.dispatchEvent(ev); 
    } 
</script> 
...