所以我有一個表單提交照片(總共8個),和我想申請一個小的影響:一旦你選擇一張照片,該按鈕可隱藏和文件名與'X'一起顯示以刪除其選擇。jQuery的事件被稱爲多次
然而,當我添加多張照片,並嘗試刪除一個,該事件被稱爲多次,越我點擊,更多的多個事件被觸發,都來自相同的元素。
任何人都可以弄明白嗎?
var Upload = {
init: function (config) {
this.config = config;
this.bindEvents();
this.counter = 1;
},
/**
* Binds all events triggered by the user.
*/
bindEvents: function() {
this.config.photoContainer.children('li').children('input[name=images]').off();
this.config.photoContainer.children('li').children('input[name=images]').on("change", this.photoAdded);
this.config.photoContainer.children('li').children('p').children('a.removePhoto').on('click', this.removePhoto);
},
/**
* Called when a new photo is selected in the input.
*/
photoAdded: function (evt) {
var self = Upload,
file = this.files[0];
$(this).hide();
$(this).parent().append('<p class="photo" style="background-color: gray; color: white;">' + file.name + ' <a class="removePhoto" style="color: red;" href="#">X</a></p>');
if(self.counter < 8) { // Adds another button if needed.
Upload.config.photoContainer.append('<li><input type="file" name="images"></li>');
self.counter++;
}
Upload.bindEvents();
},
/**
* Removes the <li> from the list.
*/
removePhoto: function (evt) {
var self = Upload;
evt.preventDefault();
$(this).off();
$(this).parent().parent().remove();
if(self.counter == 8) { // Adds a new input, if necessary.
Upload.config.photoContainer.append('<li><input type="file" name="images"></li>');
}
self.counter--;
Upload.bindEvents();
}
}
Upload.init({
photoContainer: $('ul#photo-upload')
});
每次點擊按鈕觸發事件時,它是否增加1? – Alfabravo 2012-08-08 16:33:15
看來,在'bindEvents'方法中,您的綁定事件不是需要更改的一個元素,而是所有元素。也許這會導致問題。 – tijs 2012-08-08 16:38:57
它的確增加了1,並且同一個元素一次又一次地被觸發。無論如何謝謝你 – 2012-08-08 16:58:49