简体   繁体   中英

Rewrite inline javascript to external function - this reference

I'm trying to rewrite some javascript code from an inline button onclick call to an regular javascript function.

I used the this reference in my code to remove a table column, which worked perfectly fine. Since I need to use the line of code on a few places I want it to be in a regular javascript function.

What I had:

<button type="button"  tabindex="-1" class="btn btn-secondary btn-tblrmv" onclick="if(!$(this).closest('tr').hasClass('notDeletable')){ $(this).closest('tr').remove(); }">
   <i class="mdi mdi-minus"></i>
</button>

as for the javasript function itself:

function removeTableRow(){
     if(!$(this).closest('tr').hasClass('notDeletable')){ 
          $(this).closest('tr').remove(); 
     }
}

Could someone please explain, why this isn't working as intended?

This do not work because this is not referring to the current element. Try with:

HTML:

  <button type="button" tabindex="-1" class="btn btn-secondary btn-tblrmv" onclick="removeTableRow(this)">
       <i class="mdi mdi-minus"></i>
    </button>

JS:

function removeTableRow (row) {
     if (!$(row).closest('tr').hasClass('notDeletable')) { 
          $(row).closest('tr').remove(); 
     }
}

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