[英]jQuery: How can I bind multiple elements of the same class?
I've created a div which I want to fill with a different embedded video based on which link within a series of links below that div gets clicked by a user. 我创建了一个div,我希望根据用户点击div下面的一系列链接中的哪个链接来填充不同的嵌入式视频。 Currently, the function only works only for the top link in the list.
目前,该功能仅适用于列表中的顶部链接。 Clicking on any of the links under the first produces no effect.
单击第一个下面的任何链接都不会产生任何影响。 Here's the JS:
这是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
});
});
and the HTML 和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-->
You'll probably want to use delegate. 你可能想要使用委托。 Bind only binds a single event, whereas delegate just adds event listeners.
绑定仅绑定单个事件,而委托只添加事件监听器。
That should at least get you started. 这至少应该让你开始。
I would do it like this 我会这样做的
$('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
});
Check the following code. 请检查以下代码。 It works for me.
这个对我有用。
HTML: 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: 脚本:
<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.