Ben*_*lch 15 if-statement coffeescript
当有人更改选择选项时,我一直在尝试更新总价.这是我正在使用的select元素:
<select id="payment_talks_purchased" name="payment[talks_purchased]">
<option value="1">One</option>
<option value="2">Three</option>
</select>
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的jQuery:
jQuery(document).ready(function() {
var price = $(".total-price span.price")
var save = $(".savings")
$("#payment_talks_purchased").change(function() {
var selection = $("#payment_talks_purchased").val()
if (selection == 2) {
price.html("$12");
save.css("visibility", "visible");
} else if (selection == 1) {
price.html("$5");
save.css("visibility", "hidden");
}
});
});
Run Code Online (Sandbox Code Playgroud)
它完美地运作.它将价格更改为12美元并显示折扣消息.如果我将选择选项更改回One/1,它会将文本更改回$ 5并删除折扣消息.
我将其转换为CoffeeScript,但它只在我进行第一次更改时才有效.价格已更新.但是,当我尝试将其更改回选项1时,它不会更新.
jQuery ->
price = $(".total-price span.price")
save = $(".savings")
select = $("#payment_talks_purchased")
select.change ->
selection = select.val()
if selection = 2
price.html "$12"
return save.css "visibility", "visible"
else if selection = 1
price.html "$5"
return save.css "visibility", "hidden"
Run Code Online (Sandbox Code Playgroud)
我已经工作了好几个小时,我的智慧结束了.任何帮助将不胜感激.
mu *_*ort 26
您selection = 1的if语句内部(仍然)是CoffeeScript中的一项任务,您需要将其==用于比较.试试这个:
jQuery ->
price = $(".total-price span.price")
save = $(".savings")
select = $("#payment_talks_purchased")
select.change ->
selection = select.val()
if selection == '2'
price.html "$12"
return save.css "visibility", "visible"
else if selection == '1'
price.html "$5"
return save.css "visibility", "hidden"
Run Code Online (Sandbox Code Playgroud)
此外,==转换为===你将要比较字符串,除非你想使用你的价值"投射"你的数字selection = +select.val()(感谢Trevor Burnham这个演员技巧)或parseInt(select.val(), 10).
你可以使用开关:
switch selection
when '2'
price.html "$12"
save.css "visibility", "visible"
when '1'
price.html "$5"
save.css "visibility", "hidden"
Run Code Online (Sandbox Code Playgroud)
你也可以带走return,因为函数总会返回它们的最终值.