【问题标题】:Make a working jQuery button inside Mustache.js template在 Mustache.js 模板中创建一个有效的 jQuery 按钮
【发布时间】:2014-10-12 22:16:01
【问题描述】:

我在一个项目中使用 Mustache.js,但我一直试图在模板中包含一个 jQuery 按钮。

我制作了一个模板来显示我所在州州长选举的五位候选人。在 JSON 中,我包含了他们的姓名、照片和所属党派。我将数据加载到此模板中:

{{ #governor }}
    <div class="cand-{{ head }}">
        <div class="head">
            <img src="{{ picture }}">
        </div>
        <div class="bio">
            <h5>{{ name }}</h5>
                <i class='fa fa-circle' style='color: {{ color }}'></i> {{ party }}<br>  
        </div>
    </div>
{{ /governor }}

现在,我想在派对线下方包含一个 jQuery 按钮,该按钮将隐藏其他候选人并调出一个包含详细信息的 div,该 div 将与嵌套在其中的另一个按钮一起关闭。但是,该按钮在 Mustache 模板中不起作用。它在外面工作得很好。这是我的按钮代码:

<button class="open-govA">Details</button>

<script>
$( ".open-govA" ).click(function() {
  $( ".details-govA" ).show( "slow" );
  $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").hide( "slow" );
  });

$( ".close-govA" ).click(function() {
  $( ".details-gov" ).hide( "slow" );
   $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").show( "slow" );
  });
</script>

我应该如何进行?

【问题讨论】:

  • 对动态创建的元素使用事件委托。这个问题每天都会被问很多次......应该很容易网络搜索
  • 似乎不起作用。请记住,模板位于
  • 是的,确实如此,您需要使用 on() 并委托这些事件。谷歌jquery event delegation
  • 还在挣扎。我研究了 jQuery 事件委托,但找不到任何关于在脚本模板中放置按钮的信息。我试过on(),但它只适用于模板外的按钮。
  • 不能正确使用on()

标签: jquery mustache


【解决方案1】:

正如大家已经说过的,你应该使用event delegationthe jQuery on function

<script>
  $( "#parentInPage" ).on("click", ".open-govA", function() {
    $( ".details-govA" ).show( "slow" );
    $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").hide( "slow" );
  });

  $( "#parentInPage" ).on("click", ".close-govA", function() {
    $( ".details-gov" ).hide( "slow" );
    $( ".cand-govB, .cand-govC, .cand-govD, .cand-govE").show( "slow" );
  });
</script>

如果您在附加所有这些模板的页面上没有公共元素,您可以使用"body"。请注意过度使用它 - 请参阅 jQuery ono 文档中的 Event Performance 部分。

【讨论】:

  • 感谢您的示例。我发现我没有使用正确的 #parentInPage 值。
猜你喜欢
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2021-08-14
  • 2018-11-20
相关资源
最近更新 更多