6

我不确定这是怎么做到的。我可以对我尝试使用的路线进行硬编码,但我想以正确的方式做到这一点。

我有一个下拉菜单,需要在更改时加载新页面。这基本上是我正在尝试的方式(我已经尝试了一些变体):

@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()"]

那么我到底如何将 JavaScript 中的值插入到 Scala 函数中呢?

编辑

这是我的解决方案,灵感来自公认的答案。此下拉列表在为不同组件重复使用的标记中定义,并且每个组件的基本 URL 都不同。实现这一点的方法是将基于帐户密钥生成 URL 的函数传递到下拉列表中:

@(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>

然后你可以定义一个这样的函数来传递:

@transactionsUrl(memberAccountKey: Long) = {
  @routes.Accounts.transactions(memberAccountKey)
}

@accountsDropdown(transactionDetails.getMemberAccounts(), transactionDetails.getMemberAccountKey(), transactionsUrl)
4

1 回答 1

6

您需要一种在页面中存储所有 URL 的方法,例如

<option value="@routes.Accounts.transactions(id)">Display</option>

然后onChange,你可以:

$("select[name='product']").change(function() {
  location.href = $(this).val();
});
于 2012-05-23T17:21:15.463 回答