按钮点击未跳转至更新页面求助(hover显示URL正常)
问题:点击按钮无法跳转到更新个人资料页面
当前在查看个人资料页面,点击「Apply」按钮本应跳转至updateprofile.php页面,鼠标悬停按钮时显示的URL是正确的,但点击后始终停留在当前页面。相关代码如下:
<div class="btn-block"> <button type="button" value="back" onclick="location.href='homepage.html'">Back</button> <?php echo '<a href="updateprofile.php?editid='.$edit_id.'" class="edit" title="Edit" data-toggle="tooltip"><button>Apply</button></a>' ?> </div>
问题原因
你在<a>标签内部嵌套了<button>元素,这存在两个核心问题:
- HTML规范明确禁止
<a>标签嵌套交互式元素(如<button>),这种非法结构会导致浏览器默认行为异常。 - 未指定
type="button"的<button>会被浏览器默认识别为type="submit",如果页面中存在表单(哪怕未在代码中展示),点击按钮会触发表单提交,直接阻断<a>的跳转逻辑。
解决方法
方法1:移除<button>,将<a>样式改为按钮(推荐)
直接用<a>标签实现按钮样式,彻底避免嵌套问题:
echo '<a href="updateprofile.php?editid='.$edit_id.'" class="edit btn" title="Edit" data-toggle="tooltip">Apply</a>'
给<a>添加项目中按钮对应的CSS类(比如btn),让它视觉上和按钮一致,点击即可正常跳转。
方法2:保留<button>,移除<a>,用JS实现跳转
如果必须使用<button>,可以去掉外层的<a>,通过onclick直接控制页面跳转:
echo '<button type="button" onclick="location.href=\'updateprofile.php?editid='.$edit_id.'\'" class="edit" title="Edit" data-toggle="tooltip">Apply</button>'
注意指定type="button"避免默认的表单提交行为,同时转义字符串中的单引号。
方法3:修复嵌套结构(不推荐)
如果一定要保留嵌套结构,需要给<button>添加事件阻止默认行为,强制触发跳转:
echo '<a href="updateprofile.php?editid='.$edit_id.'" class="edit" title="Edit" data-toggle="tooltip"><button type="button" onclick="event.preventDefault(); window.location.href = this.parentElement.href;">Apply</button></a>'
但这种方式不符合HTML规范,可能存在浏览器兼容问题,建议优先使用前两种方法。
内容的提问来源于stack exchange,提问作者ALIF DANIAL NASRI
相关产品推荐
相关产品推荐

