我需要在這裏實現的是添加一個click事件監聽器到一系列的span元素中,其中包含圖像縮略圖,以便讓它們可選。這些是在用戶使用相對錶單輸入文件時動態創建的。如何動態添加一個事件監聽器到NodeElement
我到目前爲止所管理的是引用新創建的包含它們的輸出元素的childNodes。
HTML:
<div id="imageBox"><output id="list"><!-- Newly created span elements here --></output></div>
與全球範圍內的相對腳本:
var father = document.getElementById('list');
var children = father.childNodes;
然後我處理的點擊全球body元素偵聽器內:
document.body.addEventListener('click', function(event) {
if (children) {
for (var i = 0; i < children.length; i++) {
children[i].addEventListener("click", function(){
if(this.style.boxShadow === '') this.style.boxShadow ='0 0 1em blue';
else this.style.boxShadow = '';}, false);
}
}
}, false);
但因爲我是期待,它只是雙擊新元素。
我試圖添加一個回調函數,該函數將上面的循環封裝在讀取和加載所選文件輸入的函數內部,但它不起作用。
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
console.log(children.length);
clickable();
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
function clickable(){
if (children) {
for (var i = 0; i < children.length; i++) {
children[i].addEventListener("click", function(){
if(this.style.boxShadow === '') this.style.boxShadow ='0 0 1em blue';
else this.style.boxShadow = '';}, false);
}
}
}
關於如何處理這個問題的任何想法,使它只需點擊一下就可以工作?
小提琴:
https://jsfiddle.net/b130p9tb/2/
的最新進展:
現在是工作,因爲它應該響應單一的點擊正確,而是試圖選擇一個以上的項目時,它僅適用於對或物品的價值不均衡,相應的數量。例如。 :有一個項目,它工作正常,但有兩個只有第二個是可選的。有三個,只有第一個和第三個,等等。
更新小提琴:https://jsfiddle.net/b130p9tb/3/
請出示您試圖添加回調,所以我們可以看到你做錯了什麼。 – Barmar
你可以通過jsfiddle分享現有的代碼或演示嗎?這將幫助我們理解實際問題。 –