【问题标题】:access $(this) with href="javascript:..." in jQuery在 jQuery 中使用 href="javascript:..." 访问 $(this)
【发布时间】:2010-09-08 19:04:02
【问题描述】:

我正在使用 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) 是未定义的。有什么想法吗?

【问题讨论】:

    标签: jquery


    【解决方案1】:

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

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

    还有你的链接:

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

    $(this) 不存在于您的函数中,因为它应该如何知道从何处调用该操作?您没有在其中传递任何引用,因此 $(this) 可以引用除 &lt;a&gt; 之外的所有内容。

    【讨论】:

    • \ 不是必需的 这有效:
    • 呵呵...我不确定是否要逃避它。我在我的 mac 键盘上寻找 \ 这么久。这有点烦人。 ;)
    【解决方案2】:

    为什么不这样:

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

    【讨论】:

    • 为了更简单,你也可以使用&lt;li class="uncheck_tagVO" id="$id"&gt;,在jQuery上你删除第二行,将第一行和第三行选择器替换为$('li.uncheck_tagVO')$('#'+this.id)
    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2011-01-14
    • 2019-08-09
    • 2012-01-02
    相关资源
    最近更新 更多