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



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

最佳答案

首先,检查<img>关闭标签。
其次,由于浏览器的安全原理,您不能通过js调度输入的click事件。
对于div来说,可以:



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()' />

07-28 03:08
查看更多