Javascript函数在Firefox中运行多次,在Chrome中只运行一次,为什么

Javascript function running multiple times in Firefox only once in Chrome, why?

本文关键字:运行 为什么 一次 Chrome Javascript 函数 Firefox      更新时间:2023-09-26

我有一个文件上传字段,我添加了一个jQuery更改到.

在chrome中,它工作得很好,loadImage函数将占位符图片替换为要上传的图片的渲染。在firefox中,以下代码渲染了3次(控制台中有3个"1",但onchange处理程序中只有一个"2"),添加图像后会删除图像。

为什么Firefox会出现这种情况,我该如何防止

Coffeescept(如果有人喜欢更好地阅读js,我可以转换):

$('#project_display_pic').change (e) ->
  console.log "2"
  value = $(this).val()
  value = value.replace("C:''fakepath''","")
  $('#display_pic_uploader > p').text(value)
  loadImage(
    e.target.files[0],
    ( (img) -> 
      console.log "1"
      $('#display_pic_preview > img').remove()
      $('#display_pic_preview').append(img)
    ),
    {maxWidth: 212}
  )

Haml,如果这有帮助的话(#project_display_pic是文件字段的id):

    #display_pic_preview
      = image_tag( @project.display_pic.medium.url, :class => "default_pic" )
    #display_pic_uploader
      %p Add display image
      = f.file_field :display_pic

查看插件的代码,它似乎调用了图像对象的onloadonerror事件的渲染回调。也许Firefox错误地将图像的缩放视为加载事件或其他什么?或者错误事件的触发可能没有充分的理由。

换句话说,一个快速解决方案可能是这样的:

# Builds a function to show the loaded image
# The function stores the last img object it received,
# and doesn't try to show the same one twice in a row
createRenderCallback = ->
  lastImg = null
  (img) ->
    return if img is lastImg # don't handle the same img twice
    # Note that if the image failed to load, `img` will be undefined
    # You may want to check for that before trying to append it
    $('#display_pic_preview > img').remove()
    $('#display_pic_preview').append(img)
    lastImg = img # remember the img
# Attach the file input's change handler (pretty much the same as before)
$('#project_display_pic').change (e) ->
  value = $(this).val().replace("C:''fakepath''","")
  $('#display_pic_uploader > p').text(value)
  loadImage e.target.files[0], createRenderCallback(), { maxWidth: 212 }

你可以在插件的代码中做一些类似的事情,以避免它重新调用回调。或者你可以从插件中记录一些东西,看看到底发生了什么。


编辑:由于将图像插入DOM似乎会触发渲染回调,因此可以尝试以下操作:

createRenderCallback = ->
  lastImg = null
  (img) ->
    return if img is lastImg
    lastImg = img # <-- Move this line to here, i.e. before inserting the image
    $('#display_pic_preview > img').remove()
    $('#display_pic_preview').append(img)

或者,您可以简单地删除事件侦听器,而不是保留lastImg 的记录

renderCallback = ->
  if img? # this function was called from an onload event
    img.onload = img.onerror = null
  else  # called from an onerror event
    @onload = @onerror = null
  $('#display_pic_preview > img').remove()
  $('#display_pic_preview').append(img) if img?
$('#project_display_pic').change (e) ->
  value = $(this).val().replace("C:''fakepath''","")
  $('#display_pic_uploader > p').text(value)
  loadImage e.target.files[0], renderCallback, { maxWidth: 212 }

firefox多次调用此函数,但出现错误。该代码也应该有效(通过检查宽度属性检查它是否是图像对象:

loadImage(file, function(image) {
        if(typeof(image.width) !== "number") { // make sure its an image and not an error
          return;
        }
}