如何通过Ajax实现Campaign播放/暂停按钮的点击切换功能
Got it, let's get this play/pause button toggle working smoothly for your campaign. Here's how to modify your existing code to swap the buttons after a successful AJAX request:
Step 1: Update the Pause Button's AJAX Script
When the user clicks the pause button and the AJAX call succeeds, we'll replace that button with the play button. We'll also ensure the tooltip works for the new dynamic element:
$(document).on('click','.pauseCampaign',function(){ // Store a reference to the clicked button to modify it later var $currentButton = $(this); var idCampaign = $currentButton.attr('id'); $.ajax({ type:'get', url:'/pauseCampaign', data:{idCampaign: idCampaign}, success:function(msg){ console.log(msg); // Replace the pause button with play button HTML $currentButton.replaceWith(` <a href="#" class="playCampaign" id="${idCampaign}" data-toggle="tooltip" title="Resume campaign" style="float: right; padding: 5px"> <i class="fa fa-play-circle fa-2x" aria-hidden="true"></i> </a> `); // Re-initialize tooltip for the new play button (dynamic elements need this) $('.playCampaign[data-toggle="tooltip"]').tooltip(); } }); });
Step 2: Add the Play Button's AJAX Script with Swap Logic
Do the reverse for the play button: after a successful AJAX call to resume the campaign, replace it with the pause button:
$(document).on('click','.playCampaign',function(){ var $currentButton = $(this); var idCampaign = $currentButton.attr('id'); $.ajax({ type:'get', url:'/playCampaign', data:{idCampaign: idCampaign}, success:function(msg){ console.log(msg); // Replace the play button with pause button HTML $currentButton.replaceWith(` <a href="#" class="pauseCampaign" id="${idCampaign}" data-toggle="tooltip" title="Pause campaign" style="float: right; padding: 5px"> <i class="fa fa-pause-circle-o fa-2x" aria-hidden="true"></i> </a> `); // Re-initialize tooltip for the new pause button $('.pauseCampaign[data-toggle="tooltip"]').tooltip(); } }); });
Key Notes
- We use
$currentButton = $(this)to keep a reference to the clicked element, preventing context loss inside the AJAX success callback. - Template strings (backticks ``) simplify writing multi-line HTML with dynamic values like
${idCampaign}. - Re-initializing the tooltip is essential because dynamically added elements don't automatically inherit the tooltip binding from the initial page load.
- Ensure your
/playCampaignbackend endpoint correctly updates the database field from 0 back to 1 to keep the campaign state in sync.
内容的提问来源于stack exchange,提问作者harunB10
相关产品推荐
相关产品推荐

