2009-07-31 55 views
3

所有我是jQuery的新手,我在使用jQuery方法操纵AJAX结果时遇到了一些问题。jQuery find()只能在AJAX结果上工作一次吗?

我使用AJAX get并对结果输出执行find方法。但是这似乎只能工作一次。在find()参数中使用相同选择器的后续尝试不起作用。不同的选择器可以工作,但是只能使用一次。

当遍历AJAX结果似乎有什么事情发生?

AJAX调用...

$.get('sections.htm', {}, function(data) { 
     var $response = $('<div />').html(data); 
     showContent("teaser"); 

     function showContent(nav) { 
      loadContent(nav); 
      loadSlimboxHack(); 
      $('#content').fadeIn(400); 
     } 

查找元素...

function loadContent(nav) { 
     if (nav == 'teaser') 
     { 
      $('#content').html($response.find('.teaser')); 
     } 

这工作,但如果我再次尝试showContent(".teaser"),它失败,因为它似乎并没有找到任何与因此#content被覆盖没有。

看看我的网站上看到...

http://www.shadowshapes.com/dev

回答

3

@redsquare, 非常感谢!这使我走上了正确的道路。

对于初学者来说,append()在单个选择器上下文中的行为类似于“移动”而不是“复制”。显然它是新手们常见的错误。它没有完全记录?我现在感觉不好! :)

http://www.nabble.com/Undocumented-move-copy-behavior-of-append%28%29-et-al.-ts21179461s27240.html#a24146606

所以我需要在另外在这种情况下使用clone()append()

$('#content').append($response.find('div.concept' + tag).clone()); 

太棒了!问题解决了!

0

从快速乍一看,我觉得你有closure问题 ...

$response变量不会在事件处理程序的关闭范围中捕获(例如,在您的点击 - >淡出 - > showContent上)。我猜如果你通过$response变量而不是试图在全​​局范围内引用它,它将会被修复。即以你的榜样,让这样的事情:

$.get('sections.htm', {}, function(data) { 
    var $response = $('<div />').html(data); 
    showContent("teaser", $response); 

    function showContent(nav, $response) { 
     loadContent(nav, $response); 
     loadSlimboxHack(); 
     $('#content').fadeIn(400); 
    } 
... 
    function loadContent(nav, $response) { 
    if (nav == 'teaser') 
    { 
     $('#content').html($response.find('.teaser')); 
    } 
... 

你保证$response将永远存在,当你去使用这种方式。另一种选择是通过在$(document).ready之外声明$response实际上是全球性的。

0

谢谢,我实际上已经尝试过在$response附近没有运气。我再次尝试了一遍,并尝试了制作$response全球的其他建议。没有运气。

奇怪的是$responseloadContent()内有效。它似乎只是一旦选择器被发现,它不再可以被“使用”?例如,一旦在页面加载会发生以下情况...

 if (nav == 'teaser') 
     { 
      $('#content').html($response.find('.teaser')); 
     } 

但随后点击传情图像之一将启动一个事件...

$('div.teaser_img').live("click", function() { 
     var nav = $(this).attr("id"); 
     $('#content').fadeOut(400, function() { 
      showContent(nav, $response); 
     }); 

然后揭开序幕conditonal内loadContent() ...

   if (nav == projects[i]) 
       { 
        var tag = '#' + nav; 
        $('#content').html($response.find('div.teaser' + tag)); 
        $('#content').append($response.find('div.concept' + tag)); 
        break; 
       } 

如此以来div.teaser已经发现加载页面时,只#content获取与写。只要还没有被使用,其他选择器也将工作。

2

您使用$ response的内容并将其中的一些添加到其他元素中。这意味着他们会摆脱美元回应并进入新家,因此选择者只能工作一次。

这样看。如果你从你的钱包中取出你的只有10美元,并把它放在我的钱包里,那么下次你看到你的钱包时就不会在那里。为什么?因为它在我的。