2011-04-20 48 views
0

我已經創建了一個div,我想用一個不同的嵌入式視頻來填充,這個視頻是根據用戶點擊某個div下面的一系列鏈接中的哪個鏈接。目前,該功能僅適用於列表中的頂部鏈接。點擊第一個鏈接下的任何鏈接都不會產生任何效果。這裏的JS:jQuery:如何綁定同一個類的多個元素?

$(document).ready(function(e){ 
$('a.videoBoxLinks').bind('click',function(e){ 
var vidUrl = $(this).attr('href'); 
var vidBox = $(this).prev('.videoBox'); 
vidBox.html('<iframe src="' + vidUrl + '" width="400" height="300" frameborder="0"></iframe>'); 
e.preventDefault(); //stops the browser click event 
}); 
}); 

和HTML

<div class="videoBox"> 
<h1>default content to be replaced</h1> 
</div> 
<a class="videoBoxLinks" href="videoURL1">Test 1</a></br> <!--this one works--> 
<a class="videoBoxLinks" href="videoURL2">Test 2</a> <!--this one doesn't--> 
+0

因此,如果你之前,首先單擊第二個鏈接,但仍然什麼都不做? – 2011-04-20 04:46:28

回答

0

檢查下面的代碼。這個對我有用。

HTML:

<div id="videoBox"> 
    <h1> 
     default content to be replaced</h1> 
</div> 
<a class="videoBoxLinks" href="videoURL1">Test 1</a><br /> 
<!--this one works--> 
<a class="videoBoxLinks" href="videoURL2">Test 2</a> 

腳本:

<script type="text/javascript"> 
    $(document).ready(function (e) { 
     $('a.videoBoxLinks').bind('click', function (e) { 
      var vidUrl = $(this).attr('href'); 
      //var vidBox = $(this).prev('.videoBox'); 
      $("#videoBox").html('<iframe src="' + vidUrl + '" width="400" height="300" frameborder="0"></iframe>');     
      e.preventDefault(); //stops the browser click event 
     }); 
    }); 

</script> 
+0

我早些時候已經接受了Rahul的答案,但是當我開始研究佈局時,我把鏈接列表放到了一個表中,只是發現它不再有效。事實證明,prevAll()只能找到兄弟姐妹 - 拉胡爾指出的(我忘了!)。該解決方案適用於所有具有目標ID的元素,這正是我所需要的。謝謝! – Chris 2011-04-26 21:12:04

0

您可能需要使用委託。綁定只綁定一個事件,而委託只是添加事件監聽器。

這應該至少讓你開始。

2

而不是

var vidBox = $(this).prev('.videoBox'); 

使用

var vidBox = $(this).prevAll('.videoBox'); 

.prev只能找到直接前置兄弟而.prevAll會發現所有前面的兄弟姐妹。

+1

jsfiddle:http://jsfiddle.net/userdude/PLvay/ – 2011-04-20 04:54:14

+0

非常感謝!那就是訣竅。 – Chris 2011-04-20 22:39:53

0

我會做這樣的

$('a.videoBoxLinks').bind('click',function(e){ 
    link = $(this); 
    // if the iframe does not exists 
    if ($('div.videoBox iframe').length == 0) { 
     // create the iframe 
     $('div.videoBox').html('<iframe width="400" height="300" frameborder="0"></iframe>'); 
    } 
    // set the source of the iframe 
    iframe = $('div.videoBox iframe').attr('src', link.attr('href')); 
    e.preventDefault(); //stops the browser click event 
}); 
相關問題