为什么我的脚本不响应类更改?

时间:2010-08-09 02:31:20

标签: jquery jquery-selectors

我已经使用jQuery已经有一段时间了,这个让我很难过 - 我真的希望我只是大脑放屁! 我有以下JS:

$(document).ready(function(){

  $('.thumb,.link').click(loadContent);

});

function loadContent() {
    alert(this.id);  
 if(this.id == 'contact')  
 {  
   $('#thumbs').hide();  
   $('#content').show().load('contact.html');

   $('#home').addClass('link');  
   $('#contact').removeClass('link');  
 }  
 else if(this.id == 'home')  
 {  
   $('#thumbs').show();  
   $('.thumb').removeClass('dim');  
   $('#content').hide();  
   $('#home').removeClass('link');  
 }  
 else  
 {  
   var projectNumber = parseInt($(this).attr('src').replace("graphics/",""));

   $('#thumbs').hide();  
   $('.thumb').removeClass('dim');  
   $('#content').show().load("projects/" + projectNumber + ".html");  
   $('#home').addClass('link');  
 }  
}

以及以下HTML:

<div id="container">  
<table id="left"><tr><td><span id="home">SOME GUY</span><br />  
<span id="all">&gt;</span>&nbsp;<span class="cat">ALL PROJECTS</span><br />
<span id="furniture">&nbsp;</span>&nbsp;<span class="cat">FURNITURE</span><br />
<span id="objects">&nbsp;</span>&nbsp;<span class="cat">OBJECTS</span><br />
<span id="graphics">&nbsp;</span>&nbsp;<span class="cat">GRAPHICS</span><br />
<span id="web">&nbsp;</span>&nbsp;<span class="cat">WEB</span><br />
<span id="contact" class="link">CONTACT</span></td></tr>
</table>
<div id="center">
<div id="thumbs"><img class="thumb furniture" src="graphics/0.png" /><img class="thumb web" src="graphics/0.png" /><img class="thumb objects" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb web" src="graphics/0.png" /><img class="thumb furniture" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb web" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb graphics" src="graphics/0.png" /><img class="thumb" src="graphics/0.png" /><img class="thumb web" src="graphics/0.png" /></div>
<div id="content"></div>
</div>
</div>

这个想法是单击“home”链接(span id =“home”),添加类“link”,使其可以根据document.ready函数进行点击。我可以看到正在添加的类,实际上它的CSS使光标成为指针,所以我知道它正在工作。但是loadContent()函数似乎没有运行 - 它应该在点击时提醒它的ID,然后显示隐藏的“拇指”div - 而这些都不会发生。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

执行link时,

$(document).ready类不存在。使用“点击”参数代替“点击”调用live

答案 1 :(得分:1)

$('.thumb,.link').click(loadContent);

应该是:

$('.thumb,.link').live('click', loadContent);

在页面加载后动态添加link类时,您需要告诉jQuery查找它的未来实例。