2010-07-25 70 views
1

的HTML:jQuery的变量的问题

<div class="first" id="first_id"> 
<div class="second">text sample</div> 
<div class="third"><button type="submit" class="some_class" id="some_id">send</button></div> 
</div> 

的Jquery:

$("#some_id").click(function() { 
var test = $(this).closest('.first').attr('id'); 
.. 
return false; 
}); 

我想在jQuery代码来代替 “第一” 采用div VAR “测试” 的内容之上。 喜欢的东西:

$("."+test).html('<img src="img/spin.gif">'); 

但是,当我在功能上把这部分代码上面这是行不通的。我做错了什么?

回答

6

你得到的ID,但其选择为.class selector(所以应该$("#"+test)),但它可以更容易,就像这样:

$("#some_id").click(function() { 
    $(this).closest('.first').html('<img src="img/spin.gif">'); 
    return false; 
}); 

没有必要再去选择的元素,你已经拥有了它,所以只是你发现.closest()作品的元素调用.html(),简单和快速:)


为了完整起见,虽然,你应该做的是这样的:

$("#some_id").click(function() { 
    $(this).closest('.first').empty().append('<img src="img/spin.gif">'); 
    return false; 
}); 

使用.empty()通话将清理click处理我们在,否则it'l围绕留在$.cache ......这不是一个大问题,但如果你有很多它加起来的元素,最好总是在可能的情况下进行清理。

1

你把id值放到测试中,但是你用'。'在选择器中。相反,你应该使用'#'。