PHP表单按钮重定向(正在更改URL),即使我不想



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

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

$value=";1.png";

当我按下它时,它会像这样更改url:

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:我不确定是什么问题,但我认为是的形式

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

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;    
}

当您未能指定<button>元素的类型时,浏览器将暗示它是submit类型的按钮。因此,当你按下按钮时,你的浏览器正在提交带有它的表格。

你也应该,

a( 指定除submit或之外的按钮类型

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

相关内容

最新更新