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. 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:
$(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
<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-->
Instead of
var vidBox = $(this).prev('.videoBox');
use
var vidBox = $(this).prevAll('.videoBox');
.prev
will only find the immediately preceding sibling whereas .prevAll
will find all preceding siblings.
Check the following code. It works for me.
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>
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
});
精彩评论