2013-06-23 32 views
0

我正在使用jQuery对话框将其他页面加载到主页上的对话框中。其他页面可能具有定位标记,并且我正在使用加载函数的已完成事件来选择加载内容的div中的所有定位标记。然后我连接锚标签点击事件处理程序,以便内容加载到主页面上包含的div。然而,这只能工作两次。当您运行下面的示例代码时,Partial1出现在对话框中。当我单击对话框中的Partial2链接时,Partial1会加载到对话框中,但是,这次单击Partial2链接时,它会加载到主页面中。我做错了什么和/或没有把握?Javascript事件和递归问题

首页/索引:

<a href="/Home/Partial1" id="help">Partial 1</a> 

<div id="dialog" style="display: none"> 

</div> 


<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#help").click(function() { 
      adjustNestedAnchors($(this)); 
      $("#dialog").dialog().show(); 
      return false; 
     }); 

     function adjustNestedAnchors(element) { 
      $("#dialog").load($(element).attr("href"), 
       function (response, status, xhr) { 
        if (status != "error") { 
         $("#dialog a").click(function() { 
           $("#dialog").load($(this).attr("href"), adjustNestedAnchors($(this))); 
           return false; 
         }); 
        } 
       }); 
     } 
    }); 
</script> 

首页/ Partial1

This is a sample partial view, which has a link back to <a href="/Home/Partial2">Partial2</a>. 

首页/ Partial2

This is a sample partial view, which has a link back to <a href="/Home/Partial1">Partial1</a>. 

回答

2

问题就是这条线:

$("#dialog").load($(this).attr("href"), adjustNestedAnchors($(this))); 

将调用链接adjustNestedAnchors呼吁divload之前,所以没有什么是调整嵌套锚后的内容已被加载。

相反,我相信你想要的东西是这样的:

<a href="/Home/Partial1" id="help">Partial 1</a> 

<div id="dialog" style="display: none"> 

</div> 


<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#help").click(function() { 
      loadDialog(this); 
      $("#dialog").dialog().show(); 
      return false; 
     }); 

     // load link in dialog, and adjust its links to load inside it 
     function loadDialog(link) { 
      $("#dialog").load($(link).attr("href"), function (response, status, xhr) { 
       $("#dialog a").click(function() { 
        loadDialog(this); 
        return false; 
       }); 
      }); 
     } 
    }); 
</script> 

(免责声明:没有测试)

请注意,我已经改名为adjustNestedAnchorsloadDialog,我认为这是一个更准确描述其主要功能。

+0

这很好用!感谢您指出我的错误和函数名称建议! – codechurn

+0

@艺术:不客气! – ruakh