将动态变量发送到jquery

时间:2017-04-28 18:00:02

标签: javascript jquery node.js ejs

我有一个用EJS模板动态构建的表。我想在用户点击按钮时将动态值传递给jQuery函数。

这就是我构建表格的方式:

<% for(var i=0; i< automated_campaigns.length; i++) { %>

...

<%= automated_campaigns[i].name %>

<td>
<button type="button" class="btn btn-danger btn" id="load" data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i>">Activate</button>

</td>

...
<% } %>

这是我处理点击事件的jQuery函数:

<script type="text/javascript">

$('.btn').on('click', function(automated_campagin_name) {
    var $this = $(this);
  $this.button('loading');

    $.get( "/automated-campaigns/change_status/" + str(automated_campaign_name), function( data ) {
      $( ".result" ).html( data );
      alert( "Load was performed." );
    });


    setTimeout(function() {
       $this.button('reset');
   }, 8000);
});

</script>

如何发送正确的campaign_name?

2 个答案:

答案 0 :(得分:3)

campaign_name放在data-campaign_name中,因为您已经为每个人循环,然后在jQuery中访问它。

$('.someElement').data('campaign_name');

答案 1 :(得分:1)

您可以在所需的每个按钮上设置数据属性:

<button type="button" data-cname="<%= automated_campaigns[i].name %>" class="btn btn-danger btn" id="load" data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i>">Activate</button>

脚本可能如下所示:

 <script type="text/javascript">

$('.btn').on('click', function(automated_campagin_name) {
    var $this = $(this);
    var cname = $this.data("cname");
  $this.button('loading');

    $.get( "/automated-campaigns/change_status/" + str(cname), function( data ) {
      $( ".result" ).html( data );
      alert( "Load was performed." );
    });


    setTimeout(function() {
       $this.button('reset');
   }, 8000);
});

</script>