【问题标题】:PHP form button redirects (is changing the URL) even if I don't want to即使我不想,PHP 表单按钮也会重定向(正在更改 URL)
【发布时间】:2021-12-18 19:00:03
【问题描述】:

所以,我在表单中有一个按钮。

   <form>
      <button onclick="alert('<?php echo $value ?>')">Click me!</button>
   </form>

$value = "1.png"

当我按下它时,网址会改变如下:

Initial: 
index.php?id=82

After I click:
index.php?

如您所见,我希望按钮仅显示警报,而不是更改 URL

完整代码:

 <form>
    <label>Title</label><br>
    <input type="text" value="<?php echo $title ?>"><br><br>
    <label>Description</label><br>
    <textarea rows="5" maxlength="120"><?php echo $desc ?></textarea><br><br>
    <div>
       <?php for($k = 0; $k < count($images); $k++) { ?>
         <div>
           <img src="<?php echo $images[$k] ?>">
           <button onclick="alert('<?php echo $images[$k] ?>')">Click me!</button>
         </div>
       <?php } ?>
    </div>
</form>

PS:我不确定是什么问题,但我认为是表格

【问题讨论】:

  • 设置按钮的类型为按钮;它是默认提交的。 &lt;button type="button" onclick="alert('&lt;?php echo $images[$k] ?&gt;')"&gt;Click me!&lt;/button&gt;

标签: php forms redirect button


【解决方案1】:

至少有两种方法可以实现:

html:

<button type="button" onclick="alert('<?php echo $images[$k] ?>');">Click me</button>
<button onclick="alert('<?php echo $images[$k] ?>');return false;">Click me!</button>

如果您唯一想要实现的目标是提醒文本,我认为第一个选项是最好的。

如果在单击按钮时调用一个函数并希望得到不同的响应,第二个选项可能会更好:

<button onclick="return foo('<?php echo $images[$k] ?>');">Click me!</button>

在 javascript 中:

function foo(image) {
    //If image is img1 then update the page
    //If any other image, don't update the page
    if (image == 'img1') {
        return true;
    }
    return false;    
}

【讨论】:

  • 添加 type="button" 属性后问题解决了,谢谢!
  • 不客气!
【解决方案2】:

当你没有指定&lt;button&gt;元素的类型时,浏览器会暗示它是submit类型的按钮。因此,当您按下按钮时,您的浏览器正在提交表单。

你应该,

a) 指定除submit 以外的按钮类型,或

b) 在运行的javascript代码中返回false,防止点击事件冒泡。

【讨论】:

  • 添加 type="button" 属性后问题解决了,谢谢!
猜你喜欢
  • 2016-07-23
  • 2012-05-29
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多