2012-02-28 65 views
1

我有一些代碼,您可以點擊鏈接並打開div。在正常狀態下,鏈接顯示「觀看視頻」,我希望它能夠工作,以便當div變爲可見時鏈接文本變爲「關閉視頻」。點擊關閉視頻鏈接關閉div。使用JQuery切換div並鏈接文本切換

這裏是什麼,我試圖做一個例子:http://jsfiddle.net/XsvG9/

下面是實際的代碼:

JS

$("span.trigger a").click(function() { 
    the_id = $(this).attr('id'); 

$("#toggle_container-"+the_id).slideToggle(500, function() { 
    $("span.trigger a"+the_id).text($(this).is(':visible') ? 'Close video' : 'Watch video'); 
    }); 
}); 

HTML

<p class="data">Posted Feb 20 | <a href="/supersecret/jsmith/post/399/">0 comments</a> |<span id="votes_count399" class="votes_count"> 0 </span> 

<span id="vote_buttons399" class="vote_buttons">faves<a id="399" title="Favorite This" class="vote_up" href="javascript:;">#</a></span> | <span class="trigger"><a id="399" href="javascript:;">Watch video</a></span> 
</p> 

<div class="hide" id="toggle_container-399" style="display: none;"> 
    <iframe width="555" height="315" frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/z1c1OIMbmb0"/></div> 
</div> 

我有在div打開的地方工作,但鏈接不切換文本。我一直盯着這太久,所以如果一雙新鮮的眼睛能夠幫助我找到錯誤,我會很感激。

感謝您的幫助。

回答

3

您的主播具有相同的編號399這是造成主要問題的原因。

而不是.text()方法,使用.html()來更改文字以及。

This demo消除了所有問題並且完美地工作。

+0

謝謝,這正是我想要的。我有一種感覺,那就是我忽略的那種簡單。 – joeschmidt 2012-02-28 05:24:15

-1

你是從你點擊鏈接獲取ID,然後使用該ID稍後創建一個選擇只是引用回「這個」

$("span.trigger a").click(function() { 
     the_id = $(this).attr('id'); 

    $(this).text($(this).is(':visible') ? 'Close video' : 'Watch video'); 

    $("#toggle_container-"+the_id).slideToggle(500); 

    return false; 
}); 

更新例如http://jsfiddle.net/XsvG9/2/

在單擊處理「這」指的是您在

+0

鏈接將始終可見,可見檢查需要在toggle_container上執行,而不是鏈接。 – 2012-02-28 03:55:34

+0

好趕上...我專注於尷尬的選擇器 – charlietfl 2012-02-28 04:18:20

0

實際點擊我會刪除多餘的跨度周圍的鏈接,切換div的ID添加到鏈接的href在您選擇的元素,然後添加文本週圍的跨度鏈接:

$(".trigger").click(function(){ 
var lnk = $(this).attr("href"); 
$(lnk).slideToggle(300, "easeInOutSine"); 
}).toggle(
    function(){ 
     $(this).children('span').html('Close ');}, 
    function(){ 
     $(this).children('span').html('Watch '); 
    }) 

Working Demo here

1

你需要知道的第一件事情是,你不能使用重複的ID。您有兩個具有相同ID的錨點 - 這是無效的,只會導致同一頁面上有多個影片出現問題。如果您將ID存儲在數據屬性中,則可以重新使用它以選擇要顯示的正確影片元素。你也應該給你的錨類,所以你可以控制不同的功能(喜愛,切換等)

HTML:

<a href="javascript:;" data-movie-id="399" class="watch">Watch video</a> 

JS:

$("span.trigger a.watch").click(function() { 
    the_id = $(this).attr('data-movie-id'); 
    anchor = $(this); 

    $("#toggle_container-" + the_id).slideToggle(500, function() { 
     anchor.text($(this).is(':visible') ? 'Close video' : 'Watch video'); 

    }); 
}); 

工作的jsfiddle:http://jsfiddle.net/XsvG9/7/

+0

謝謝,我會給這個嘗試以及它似乎有點清理的東西。 – joeschmidt 2012-02-28 05:28:23