Norbert
Norbert

Reputation: 2771

jQuery: Using $(this) Inside 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;
}

Upvotes: 3

Views: 4745

Answers (3)

RoToRa
RoToRa

Reputation: 38441

Pass a reference 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;
}

Upvotes: 7

user113716
user113716

Reputation: 322622

You can use .call() to set the value of this as you requested.

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

Now in the deletePerson function, this will be the element.

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

Upvotes: 3

Seth
Seth

Reputation: 6260

You don't need to have JS on the link itself since you're 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;

});

Upvotes: 0

Related Questions