开发者

jQuery: Using $(this) Inside Functions?

开发者 https://www.devze.com 2023-02-14 16:15 出处:网络
Is there a way to use $(this) inside jQuery functi开发者_如何学Pythonons? HTML <ul> <li class=\"delete\"><a onclick=\"deletePerson(12);\" href=\"\">Delete</a></li>

Is there a way to use $(this) inside jQuery functi开发者_如何学Pythonons?

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;
}


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;
}


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;
}


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;

});
0

精彩评论

暂无评论...
验证码 换一张
取 消