You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移除上传图片预览时页面自动刷新的问题排查求助

Hey there! Let's figure out why your page is refreshing when you click the delete button—this is a common gotcha with anchor tags in HTML.

The Root Cause

Your delete button is nested inside an <a> tag with href="javascript:removeImage()". Even though you're calling a JavaScript function here, the anchor tag's default behavior (navigating to a new URL) is still being triggered after your function runs. Since the href uses a javascript pseudo-url, it ends up reloading the current page, which wipes out all user input.

Fixes You Can Implement

Here are a couple of solid ways to resolve this:

1. Prevent Default Behavior in the removeImage Function

Modify your removeImage function to explicitly stop the anchor tag from navigating. First, update the anchor tag to pass the event object:

<a id="removeBttnFrame" href="javascript:removeImage(event)"></a>

Then update the removeImage function to block the default action:

function removeImage(event) {
  // Stop the anchor tag's default navigation behavior
  event.preventDefault();
  
  $('#preview').attr('src', 'Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png');
}

2. Replace the Anchor Tag with a Non-Navigable Element

Since you're using the anchor tag just as a container for the button, swap it out for a <div> to eliminate default navigation behavior entirely:

<!-- Replace the <a> tag with a div -->
<div id="removeBttnFrame"></div>

3. Attach the Click Event Directly to the Button

A cleaner approach is to add a click listener directly to the delete button when you create it, removing the need for the anchor tag's href:

function addDeleteBttn() {
  var removeBttn = document.createElement("BUTTON");
  removeBttn.title="Entfernen";
  removeBttn.innerHTML='<i class="fa fa-trash-o"></i>';
  removeBttn.className="removeBttnClass";
  
  // Add click event directly to the button
  removeBttn.addEventListener('click', function() {
    $('#preview').attr('src', 'Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png');
  });
  
  document.getElementById("removeBttnFrame").appendChild(removeBttn);
}

Bonus: Clean Up Redundant Code

I noticed in your original removeImage function you're setting the src twice—you can remove the line $('#preview').attr('src', 'noimage.jpg'); since it's immediately overwritten by the default image path.

Give one of these fixes a try, and your page should stop refreshing when you delete the preview image, keeping all user input intact!

内容的提问来源于stack exchange,提问作者armel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:20:15