如何在 PHP 中将 JS 确认添加到动态创建的按钮

How to add JS confirm to dynamicly created button in PHP

我的应用动态生成 href。如何添加JS确认onClick? 到目前为止,我已经尝试过这个:

echo'<a type="button" onClick="return confirm("Are you sure?")" 
class="btn btn-danger" href="delete.php?id='.$this->articleId.'" >Delete</a>';

而且它不起作用。任何想法如何解决它?谢谢:)

试试这个:

echo'<a type="button" onClick="return confirm(\'Are you sure?\')"
class="btn btn-danger" href="delete.php?id='.$this->articleId.'" >Delete</a>';>';

请注意 " 破坏了您的代码:

onClick="return confirm("Are you sure?")" 

该行实际上分为三行:

onClick="return confirm(" //Ends here because the code is from " -> "
Are you sure? //This is nothing to the code and cannot be run
")" //This is another string

因此正确的方法如下:

onClick="return confirm('Are you sure?')"