2012-04-24 56 views
0

我也試着做一個頁面,將加載YouTube視頻,而無需重新加載頁面,當一個鏈接被點擊。我有代碼的時候被按下按鈕的工作,它看起來像:使用JavaScript點擊鏈接時,在YouTube上搜索視頻?

$(document).ready(function() { 
    $(".button").click(function() { 
     var search = $(".input").val(); 
     var keyword= encodeURIComponent(search); 
     var yt_url='http://gdata.youtube.com/feeds/api/videos?q='+keyword+'&format=5&max-results=1&v=2&alt=jsonc'; 

$.ajax({ 
     type: "GET", 
     url: yt_url, 
     dataType:"jsonp", 
     success: function(response) { 
      if(response.data.items) { 
       $.each(response.data.items, function(i,data) { 
        var video_id=data.id; 
        var video_frame="<iframe width='420' height='236' src='http://www.youtube.com/embed/"+video_id+"' frameborder='0' type='text/html'></iframe>"; 
        $("#video").html(video_frame); 
       }); 
      } else { 
       $("#video").html("<div id='no'>No Video</div>"); 
      } 
     } 
    }); 
}); 
}); 

我一直在試圖改變從一個教程我在網上遵循了這一代碼,以獲得鏈接工作。雖然我不確定接下來應該做什麼,但我嘗試更改類,但在從鏈接獲取搜索數據時遇到了問題。我想這對提高是:

<div id="main_section"> 
    <div id=ytVid> 
     <iframe width="480" height="360" src="http://www.youtube.com/embed/xJ3-NnNx6Zs" frameborder="0" allowfullscreen></iframe> 
    </div> 
    <p id="1">Jackie Wilson - Reet Petite</p> 
    <p id="2">Queen - Bohemian Rhapsody</p> 
</div> 

當有人點擊「傑克威爾森 - REET嬌小」的文字或鏈接,它將更新的YouTube視頻,也將女王歌曲。

感謝

編輯: 我改變了JavaScript文件到這一點:

$(document).ready(function() { 
    $("#songInfo").click(function() { 
    function openLink(evt) { 
      var search = evt.target.innerHTML; 
      var keyword= encodeURIComponent(search); 
      ... rest of code ... 

和HTML到:

<p id="1" onclick="openLink(evt);"> Jackie Wilson - Reet Petite</p> 
<p id="2" onclick="openLink(evt);"> Queen - Bohemian Rhapsody</p> 

當我點擊了文字什麼都沒有發生 對不起,我在HTML中對JavaScript很新穎,我早就應該說過了。

回答

0

我想你會有同樣的事情做<p>標籤的「onclick」事件 - documentation說它對這些標籤有效。事情是這樣的:

document.getElementById("1").onclick = "openLink(evt);"; 

然後,如果你需要的<p>標籤的文字,嘗試這樣的事情:

function openLink(evt) { 
    var search = evt.target.innerHTML; 
    var keyword= encodeURIComponent(search); 
    ... // just like your unnamed function 
} 
+0

我想你的代碼,但我不能得到它的工作,我已經把一個我上面做的例子。 – user1346670 2012-04-24 14:46:31

+0

我不熟悉你的'$(「#video」)'語法。這相當於調用'getElementById()'?對不起,我已經做了相當多的JavaScript,但我遠離專家。 – 2012-04-25 13:05:27

相關問題