jQuery:如何绑定同一个类的多个元素?

时间:2011-04-20 04:44:00

标签: javascript jquery bind

我创建了一个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-->

4 个答案:

答案 0 :(得分:2)

而不是

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

使用

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

.prev只会找到前一个兄弟姐妹,而.prevAll会找到所有前面的兄弟姐妹。

答案 1 :(得分:0)

你可能想要使用委托。绑定仅绑定单个事件,而委托只添加事件监听器。

至少应该让你开始。

答案 2 :(得分: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
});

答案 3 :(得分: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>
相关问题