简体   繁体   中英

Dynamically created popover with buttons

I am normally a backend dev; but for this I know I am getting caught out by not working within the how the web browser works.

I left the JavaScript alert in there for ease of use. depending on which button you clicked in the popover it should popup and say leave-X or office-x where X is the ID of the which the button was a part of.

But they all say "leave-1" or "office-1" regardless of which field I choose. I know I am pulling the correct data from the correct field as changing "1" to say "foo" it will display office-foo.

I would rather not have a separate bespoke popover for each table-cell as that would be hundreds of entries in the final product.

My basic 2x2 table & jQuery/bootstrap code:

<div class="container">
  <table class="table table-striped">
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
    </tr>
    <tr>
      <td data-placement="bottom" tabindex=-1 data-toggle="popover" data-trigger="focus" data-container="body" id="1" class="td-Office">1</td>
      <td data-placement="bottom" tabindex=-1 data-toggle="popover" data-trigger="focus" data-container="body" id="2" class="td-Office">2</td>
    </tr>
    <tr>
      <td data-placement="bottom" tabindex=-1 data-toggle="popover" data-trigger="focus" data-container="body" id="3" class="td-Office">3</td>
      <td data-placement="bottom" tabindex=-1 data-toggle="popover" data-trigger="focus" data-container="body" id="4" class="td-Office">4</td>
    </tr>
  </table>
</div>




var parentClass = $("[data-toggle=popover]").attr('id');
$("[data-toggle=popover]").popover({html: true, content: `<div id="popover-content">
    <button id="office-`+ parentClass +`" class="btn btn-sm btn-Office" onclick="toggleTD(this);">Office</button>
    <button id="leave-`+ parentClass +`" class="btn btn-sm btn-Leave" onclick="toggleTD(this);">Leave</button>
  </div>`});

$('.popover-dismiss').popover({
  trigger: 'focus'
}) 
function toggleTD(elm) {
    alert(elm.id);
}

The problems is that parentClass value is always "1";

If you want to use the button id, replace the content with a function, and use this.id:

$("[data-toggle=popover]").popover({
   html: true, 
   content: function() { 
      return `<div id="popover-content">
               <button id="office-`+ this.id +`" class="btn btn-sm btn-Office" onclick="toggleTD(this);">Office</button>
               <button id="leave-`+ this.id +`" class="btn btn-sm btn-Leave" onclick="toggleTD(this);">Leave</button>
            </div>`
   }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM