2011-05-23 77 views
0

嗨,有人可以幫助我改變這種編碼我試圖刪除href頁面#.html加載並使用預加載li與文本來填充單擊鏈接時的sclit div。更改jQuery加載代碼

<div id="sclit"></div> 
<!-- old code 
<a href="page1.html" class="para">Sci Lit 1</a> 
<a href="page2.html" class="para">Sci Lit 2</a> 
<a href="page3.html" class="para">Sci Lit 3</a> 
--> 

<ul style="display:none"> 
<li class="page1"> text text </li> 
<li class="page2"> text text </li> 
<li class="page3"> text text </li> 
</ul> 

<script> 
jQuery(document).ready(function() { 
    jQuery(".para").click(function() { 
     // jQuery("#sclit").load(jQuery(this).attr('href')); // old code 
     jQuery("#sclit").load(jQuery(this).attr('li')); 
    }); 
}); 
</script> 
+1

您是否試圖將每個錨中的href頁面預加載到'li'中,然後在單擊'a'時將它們交換出來? – hunter 2011-05-23 14:45:12

回答

3

我覺得你只是想消除.load在這種情況下,你可以做這樣的事情:

http://jsfiddle.net/GgMee/

將html標記更改爲:

<div id="sclit"></div> 

<a href="javascript:void(0)" class="para">Sci Lit 1</a> 
<div class="details">text for sci lit 1</div> 

<a href="javascript:void(0)" class="para">Sci Lit 2</a> 
<div class="details">text for sci lit 2</div> 

<a href="javascript:void(0)" class="para">Sci Lit 3</a> 
<div class="details">text for sci lit 3</div> 

其中隱藏每個鏈接後的details div,幷包含單擊該鏈接時要顯示的文本。

然後jQuery是這樣的:

$(function(){ 
    $(".para").click(function(){ 
     $("#sclit").text($(this).next(".details").text()); 
    }); 
}); 

點擊一個鏈接時,發現它後details DIV,並把文字從入sclit格。

+0

快速問題,我將如何預先載入Sci Lit 1? – acctman 2011-05-23 16:08:15

+0

如果我正確理解你想要的東西,我上面發佈的html就是你想從後端返回的東西。這樣,當它們點擊並且不需要ajax時,它就會在那裏。如果您希望它默認爲sci lit的文本,那麼您可以在創建html時將其從後端填充,或者在準備好的文檔中將其設置爲您的javascript。 – 2011-05-23 17:49:06

+0

使用文檔準備就需要jquery吧? – acctman 2011-05-25 21:26:38

2
jQuery(function() { 
    // preload all li's with the content of each anchors href beforehand 
    jQuery(".para").each(function(e) { 
     var $li = $("<li />").load($(this).attr('href')); 
     $("ul").append($li); 
    }); 

    // now that data is already present in the li's (and if the indexes match up 
    // which they should if your html is accurate) swap the divs html with 
    // the content of the corresponding li 
    jQuery(".para").click(function(e) { 
     e.preventDefault(); 
     jQuery("#sclit").html($("ul li:eq(" + $(this).index() + ")")); 
    }); 
}); 
2

我不知道如果我理解正確的問題,但如果我沒看錯的要求是

  1. 用戶點擊一個L1標籤
  2. 股利sclit取文本來自li標籤。

如果這是正確的,那麼這應該這樣做

<div id="sclit"></div> 
<!-- old code 
<a href="page1.html" class="para">Sci Lit 1</a> 
<a href="page2.html" class="para">Sci Lit 2</a> 
<a href="page3.html" class="para">Sci Lit 3</a> 
--> 

<ul style="display:none"> 
<li class="page1"> text text </li> 
<li class="page2"> text text </li> 
<li class="page3"> text text </li> 
</ul> 

<script> 
jQuery(document).ready(function() { 
    jQuery("li").click(function() { 
     // jQuery("#sclit").load(jQuery(this).attr('href')); // old code 
     jQuery("#sclit").html(jQuery(this).text()); 
    }); 
}); 
</script>