问题描述
我收到以下 sweet alert 2
消息:
<button onclick='
Swal.fire({
title: "Select a page you want to be redirected:",showDenyButton: true,showCancelButton: true,confirmButtonText: "Home",denyButtonText: "About",}).then((result) => {
/* Read more about isConfirmed,isDenied below */
if (result.isConfirmed) {
Swal.fire("Saved!","","success");
} else if (result.isDenied) {
Swal.fire("Changes are not saved!","info");
}
});
'>SHOW SWEET ALERT</button>
该设计看起来工作正常,但问题是我无法执行 .erb
命令而不是显示另一个甜蜜的警报消息!
例如,如果我将上面的代码更改为以下代码,它会将一切搞砸,我不知道是什么原因造成的!:
<button onclick='
Swal.fire({
title: "Select a page you want to be redirected:",isDenied below */
if (result.isConfirmed) {
<%= link_to "Home Page",root_path,class:"navbar-brand" %>
} else if (result.isDenied) {
<%= link_to "About Page",home_about_path,class:"nav-link" %>
}
});
'>SHOW SWEET ALERT</button>
代码片段 2 将给出以下错误:Uncaught SyntaxError: Unexpected token '<'
第一个片段的图像示例:
解决方法
实际上这是预期的行为。
正如您在第二个屏幕截图中看到的,ERB 解析器在您的 JavaScript 代码中生成了正确的锚标记,从而导致了 SyntaxError。 (你不能在 JavaScript 中使用 HTML!除非它们在字符串引号周围。)
你想做的是:
<button onclick='
Swal.fire({
title: "Select a page you want to be redirected:",showDenyButton: true,showCancelButton: true,confirmButtonText: "Home",denyButtonText: "About",}).then((result) => {
/* Read more about isConfirmed,isDenied below */
if (result.isConfirmed) {
location.pathname = "<%= root_path %>"
} else if (result.isDenied) {
location.pathname = "<%= home_about_path %>"
}
});
'>SHOW SWEET ALERT</button>
"location.pathname = x" 将引导您到相对路径。
服务器的 ERB 解析器将用您要查找的路径替换 root_path 和 home_about_path 变量。