[英]How to execute a rails command with sweet alert 2?
我有以下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:",
showDenyButton: true,
showCancelButton: true,
confirmButtonText: "Home",
denyButtonText: "About",
}).then((result) => {
/* Read more about isConfirmed, 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 變量替換為您正在尋找的路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.