JQuery:执行函数后隐藏Div(奇怪的选择器)

时间:2012-06-25 01:14:30

标签: jquery css selector

我有一段很复杂的代码(JQuery和HTML5 Web SQL),可以从数据库中删除信息。但是,虽然数据库删除工作正常,但我希望在此期间使信息从视图中消失(直到页面刷新并再次查询数据库)。

我很确定这只是让选择器正确的问题

目前我有

$('.remove_event').live('click', function() {
    //TRIGGERS SQL REMOVE
    mbffdb.webdb.deleteevent($(this).attr('id')),
    //MAKES INFO DISSAPPEAR
    $(this).attr('id').addClass('displaynone');
});//END CLICK

信息在div中被赋予动态id :$(this).attr('id')(要在要删除的SQL语句中使用该ID。)

如果有人能帮助我那真的很棒!

3 个答案:

答案 0 :(得分:2)

问题是,你将一个类...添加到字符串中。 跟我来:

$(this) 

是一个元素

$(this).attr("id") 

是它的属性“id”的值,即一个字符串,因此你不能为它添加一个类。

顺便说一句,您要添加 id 还是?目前尚不清楚。如果您要添加ID,请使用.attr("id","mynewid")。如果要添加课程,请使用$(this).addClass("class")


编辑:您可能被JQuery的可链接性误导,即许多在JQUery元素或元素集上运行的函数返回另一个元素或元素集。

例如:

$("div.mydiv").parent().next().find("p").removeClass("otherclass");
              ^        ^      ^         ^

在每次调用(^)中,函数返回其他元素,因此您可以附加另一个函数来操作这些元素,连接更多元素等等。 但是对于某些功能来说并非如此:

.val() .text() .html()

返回“纯”值,而不是元素,所以在它们之后使用像addClass()这样仍然运行con元素的函数是没有意义的。

答案 1 :(得分:2)

$(this).attr('id').addClass('displaynone');更改为此$(this).addClass('displaynone');

答案 2 :(得分:0)

$('.remove_event').live('click', function() {
    // $(this) refers to the element that was clicked.
    // $(this).attr('id') will return the attribute "id" of the element

    // TRIGGERS SQL REMOVE
    // the line below will execute the "deleteevent" function
    // passing the attribute id of $(this) as a parameter.
    mbffdb.webdb.deleteevent($(this).attr('id')),

    // MAKES INFO DISSAPPEAR
    // the line below will not work because you're trying to add a class 
    // to a non-element. ($(this).attr('id') returns the attribute! 
    // you can't chain!)
    // $(this).attr('id').addClass('displaynone');

    // Instead you should use this line 
    // which will add a class "displaynone" to the element $(this)
    $(this).addClass('displaynone');
    // or you can also set 'style="display:none;"' by doing
    $(this).css('display', 'none');
});//END CLICK