在JQuery中使用href =" javascript:..."访问$(this)

时间:2020-03-05 18:52:40  来源:igfitidea点击:

我正在使用JQuery。我用下一个html调用javascript函数:

<li><span><a href="javascript:uncheckEl('tagVO-$id')">$tagname</a></span></li>

我想删除li元素,我认为使用$(this)对象很容易。这是我的javascript函数:

function uncheckEl(id) {
    $("#"+id+"").attr("checked","");
    $("#"+id+"").parent("li").css("color","black");                 
    $(this).parent("li").remove();  // This is not working
    retrieveItems();
}

但是$(this)是不确定的。有任何想法吗?

解决方案

回答

尝试这样的事情(例如隐藏&lt;li>):

function unCheckEl(id, ref) {
  (...)
  $(ref).parent().parent().hide(); // this should be your <li>
}

和链接:

<a href="javascript:uncheckEl('tagVO-$id', $(this))">

$(this)`在函数中不存在,因为它应该如何知道从何处调用操作?我们没有传递任何引用,因此$(this)可以引用除<a>以外的所有内容。

回答

为什么不这样:

<li id="uncheck_tagVO-$id">$tagname</li>

$('li').click( function() {
    var id = this.id.split("_")[1];
    $('#'+id).attr("checked","").parent("li").css("color","black"); 
    $(this).remove();
    retrieveItems();
});