[英]jQuery: How can I bind multiple elements of the same class?
我創建了一個div,我希望根據用戶點擊div下面的一系列鏈接中的哪個鏈接來填充不同的嵌入式視頻。 目前,該功能僅適用於列表中的頂部鏈接。 單擊第一個下面的任何鏈接都不會產生任何影響。 這是JS:
$(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-->
你可能想要使用委托。 綁定僅綁定單個事件,而委托只添加事件監聽器。
這至少應該讓你開始。
我會這樣做的
$('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
});
請檢查以下代碼。 這個對我有用。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.