JQuery: Using $ (this) internal functions?

Is there a way to use $(this)inside jQuery functions?

HTML

<ul>
  <li class="delete"><a onclick="deletePerson(12);" href="">Delete</a></li>
</ul>

JQuery

function deletePerson(id) {
  $(this).parent().remove(); // doesn't work
  // [...]
  return false;
}
+3
source share
3 answers

You can use .call()to set the value thisas you wish.

<a onclick="deletePerson.call( this, 12 );" href="">Delete</a>

Now the deletePersonfunction thiswill be an element.

function deletePerson(id) {
  $(this).parent().remove(); // will work
  // [...]
  return false;
}
+3
source

Pass the link as a parameter:

<ul>
  <li class="delete"><a onclick="deletePerson(this, 12);" href="">Delete</a></li>
</ul>

function deletePerson(link, id) {
  $(link).parent().remove(); 
  // [...]
  return false;
}
+7
source

You do not need to have JS in the link itself, since you are using JS.

HTML

<ul>
    <li class="delete"><a onclick="deletePerson(12);" href="">Delete</a></li>
</ul>

JQuery

$('.delete').find('a').bind('click', function() {

    $(this).parent().remove();
    return false;

});
0
source

Source: https://habr.com/ru/post/1796302/


All Articles