我正在使用 ejs 创建一个带有预订表单的快捷应用程序,并在其中添加功能。它用作付款。
我有一个select tag
并存储它的 selected text
变量内部。控制台记录它给出了值,但在实际代码中使用它会给出一个错误,指出它是未定义的。
我需要的是获取所选输入的值,例如 2
并将其乘以tour.price金额,例如34000
所以总数是 68000
并放入 addCommas() Amount: $ <%= addCommas(34000 * 2) %>
内//the total should be 68000 then the function addCommas() which would make it 68,000
.
我尝试使用 ejs 的 Scriptlet' 标签并将此代码放在文件顶部
<%let selectedText = document.querySelector("#numOfPersons")%>
<%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %>
<form>
<div>
<label for="numOfPersons">Number of Persons</label>
<select id="numOfPersons">
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</div>
Amount: $ <%= addCommas(tour.price * valueOfSelected) %> //addCommas() is a function that takes a number and adds comma every three numbers, ex: 100000 will become 100,000.
// tour.price is the total amount of the product. It's a Number. it's current value is 34000
</form>
它表示 valueOfSelected 未定义。
我的第二次尝试是添加
<%let selectedText = document.querySelector("#numOfPersons")%>
<%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %>
在表单标签下方,但它也说未定义。
然后我尝试在文件下面添加脚本标签
<script>
let selectedText = document.querySelector("#numOfPersons");
let valueOfSelected =
selectedText.options[selectedText.selectedIndex].value;
</script>
然后,为了我的最后一次尝试,我这样做了。
let totalAmount = tour.price * Number(valueOfSelected);
document.querySelector("#total").innerHTML = "Amount: $ <%= addCommas(totalAmount) %>"
所有结果均未定义
当<%= addCommas(tour.price * valueOfSelected) %>
时,预期结果应输出总价为68,000美元被称为
附注由于某种原因,我无法使用 4 个空格创建另一个代码块。
最佳答案
任何 DOM 操作(例如获取选定文本)都不能直接写入 ejs 文件中。您必须在脚本标记内执行此操作(即使用 js),就像第二种方法一样。
在脚本内部尝试在加载文档后获取值:
<script>
function addCommas() { // implement the function here }
document.addEventListener("DOMContentLoaded", function(event) {
// get values here like the `valueOfSelected`
var tourPrice = "<%= tour.price %>";
var valueWithCommasAdded = addCommas(tourPrice * valueOfSelected);
var content = document.createTextNode("Amount: " + valueWithCommasAdded);
// Finally append to the form
document.forms[0].appendChild(content);
});
</script>
您必须这样做,因为您必须等待文档完全加载。在您可以从 DOM 获取值之前,ejs 已经加载。您必须使用 javascript 动态进行计算并将其放入 DOM 中。
关于javascript - 有没有办法在ejs中的函数内添加算术运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53946550/