开发者

jQuery: Using $(this) Inside Functions?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜