在Play模板中混合JavaScript和Scala [英] Mixing JavaScript and Scala in a Play template
问题描述
我不确定该怎么做.我可以对要使用的路线进行硬编码,但我想以正确的方式做到这一点.
I'm not sure how this is done. I could hard code the route I'm trying to use, but I'd like to do this the right way.
我有一个下拉列表,需要在更改时加载新页面.基本上,这就是我要尝试的方式(我已经尝试了一些变体):
I have a dropdown that needs to load a new page on change. Here's basically how I'm trying to do it (I've tried a few variations of this):
@getRoute(value: String) = @{
routes.Accounts.transactions(Long.valueOf(value))
}
<script type="text/javascript">
$(function() {
$("select[name='product']").change(function() {
location.href = @getRoute($(this).val());
}).focus();
$('a.view.summary').attr('href', "@routes.Accounts.index()" + "?selectedAccountKey=" + $('select[name=product]').val());
});
</script>
这将产生一个identifier expected but 'val' found
异常.我还尝试将其用引号引起来,但这会导致[NumberFormatException: For input string: "$(this).val()"]
This produces a identifier expected but 'val' found
exception. I also tried surrounding it in quotes, but that causes a [NumberFormatException: For input string: "$(this).val()"]
那么我该如何将JavaScript中的值插入Scala函数中?
So how the heck do I insert a value from JavaScript into a Scala function?
修改
这是我的解决方案,受到公认答案的启发.此下拉列表是在一个标签中定义的,该标签可供不同组件重复使用,并且每个组件的基本URL不同.实现此目的的方法是将一个基于帐户密钥生成URL的函数传递给下拉菜单:
Here's my solution, inspired by the accepted answer. This dropdown is defined in a tag that's made for reuse by different components, and the base URL is different for each component. The way to achieve this was to pass a function that generates a URL based on an account key into the dropdown:
@(accountList: List[models.MemberAccount],
selectedAccountKey: Long,
urlGenerator: (Long) => Html
)
<select name="product">
@for(account <- accountList) {
@if(account.accountKey == selectedAccountKey) {
<option selected="selected" value="@urlGenerator(account.accountKey)">@account.description (@account.startDate)</option>
} else {
<option value="@urlGenerator(account.accountKey)">@account.description (@account.startDate)</option>
}
}
</select>
<script type="text/javascript">
$(function() {
$('select[name=product]').change(function() {
location.href = $(this).val();
});
});
</script>
然后,您可以定义如下函数以传递:
Then you can define a function like this to pass in:
@transactionsUrl(memberAccountKey: Long) = {
@routes.Accounts.transactions(memberAccountKey)
}
@accountsDropdown(transactionDetails.getMemberAccounts(), transactionDetails.getMemberAccountKey(), transactionsUrl)
推荐答案
您需要一种在页面中存储所有URL的方法,例如
You need a way of storing all URLs in the page, e.g.
<option value="@routes.Accounts.transactions(id)">Display</option>
然后onChange,您可以:
Then onChange, you can:
$("select[name='product']").change(function() {
location.href = $(this).val();
});
这篇关于在Play模板中混合JavaScript和Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!