Sending dynamic variable to jquery

别说谁变了你拦得住时间么 提交于 2019-12-25 09:02:06

问题


I have a table that is built dynamically with EJS template. I want to pass a dynamic value to a jQuery function when the user clicks on the button.

This is how I'm building my table:

<% 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>

...
<% } %>

And this is my jQuery function that handles the click event:

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

How can I send the right campaign_name?


回答1:


Put the campaign_name in a data-campaign_name since you are already looping for each of them then access it in jQuery.

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



回答2:


You can set data-attribute on every button you need:

<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 can looks like this:

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


来源:https://stackoverflow.com/questions/43686294/sending-dynamic-variable-to-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!