为什么输入类型='文件'不发送活动?

时间:2017-11-08 09:09:19

标签: javascript html events javascript-events event-handling

为什么这个简单示例不起作用?:

<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>

3 个答案:

答案 0 :(得分:1)

确实存在某些安全隐患,但根据您的目标,如果您将Event构造函数更改为MouseEvent,则该示例将起作用。

...
<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>
...

答案 1 :(得分:0)

首先,检查<img>关闭代码。 其次,由于浏览器的安全原则,您无法通过js调度输入的click事件。 对于div,它会没问题:

&#13;
&#13;
function imageLoad() { 
    let image = document.querySelector('#div');
    let ev = new Event('click', {bubbles: true});
    image.dispatchEvent(ev); 
  }
  
function clickDiv(){
  console.log('clicked the div');
}
&#13;
<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()' />
&#13;
&#13;
&#13;

答案 2 :(得分:0)

对后面的人重复Peter Pajchl

<!-- an ugly file input (quick, hide it away!) -->
<input
    type="file"
    id="htmlFileInputElement"
    style="position: absolute; top: -1000px; left: -1000px;"
/>


<!-- a beautiful, inviting button -->
<button onclick="
    htmlFileInputElement.dispatchEvent(
        new MouseEvent('click', { bubbles: true })
    )
">Upload File</button>

(因为此页面是文件输入样式和所有样式的第一个搜索命中)