簡體   English   中英

無法處理“ onchange”事件的處理程序

[英]Not working handler on “onchange” event

在嘗試使用“輸入文件” HTML5元素選擇圖像后,我試圖在DOM中進行一些更改。 因此,我向“ onchange”事件添加了一個處理程序,但是它不起作用!

<span class="btn-file" >
    Load and show alert 
    <input type="file" onchange="performSomeActions()"/>
</span>

假設這是函數:

function performSomeActions(){
    alert("lalala");
}

執行代碼並選擇文件后出現的錯誤是:

Uncaught ReferenceError: performSomeActions is not defined 

我以為事件名稱可能是我錯的,但是如果您用下面的行替換輸入定義,那么它將起作用!

<input type="file" onchange="alert('alo');"/>

劇場http : //jsfiddle.net/pvhaggrv/5/

提前致謝!

DEMO

HTML:

<span class="btn-file" >
    Load and show alert 
    <input type="file" id="input">
</span>

<br/>
<img id="img"> </img>

腳本:

function handleFiles() {
    alert("lol");
  var fileList = this.files; /* now you can work with the file list */
}
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);

資源:

動態添加變更監聽器

JSFiddle不喜歡對html中嵌入的javascript的調用。 為了保持代碼干凈,事件處理程序是通過javascript分配的。 將您的html更改為:

<input type="file" id='fileInput'/>

然后在你的JS中

document.getElementById('fileInput').onchange = function() {
    performSomeActions();
}

工作提琴: http : //jsfiddle.net/bmartinelle/rhbphvhu/

只是在body標簽結束之前將javascript函數放在body標簽中

<span class="btn-file" >
    Load and show alert 
    <input type="file" id="file" onchange="performSomeActions();"/>

</span>
<br/>
<img id="img"> </img>
<script>
     var performSomeActions=function(){
    alert("yyy");
}
</script>

看小提琴

您的小提琴不起作用,因為小提琴會在匿名函數中執行所有JavaScript:

//<![CDATA[ 
window.onload=function(){
function performSomeActions(){
    alert("yyy");
}

}//]]>  

因此,您的函數不在全局范圍內,您的HTML也看不到它。

為了使您的代碼正常工作,您需要直接在HEAD處包含函數,您可以通過更改左側的復選框來完成此操作: http : //jsfiddle.net/pvhaggrv/12/

但是,您不應以這種方式添加事件偵聽器,而應使用kougiland在他的回答中所說的addEventListener。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM