如何使用javascript更改ID onClick并重置其他功能

时间:2016-09-02 14:55:54

标签: javascript html

这是我想要做的一个例子:

<iframe id="toChange" width="560" height="315" src="https://www.youtube.com/embed/FirstLink" frameborder="0" allowfullscreen></iframe>

<a id="__1__" onclick="changeto1()" >  Video 1</a>
<a id="__2__" onclick="changeto2()" >  Video 2</a>
<a id="__3__" onclick="changeto3()" >  Video 3</a>


<script>
 function changeto1(){
document.getElementById('toChange').src='https://www.youtube.com/embed/LINK1';
document.getElementById('__1__').id="active";
 }

 function changeto2(){
document.getElementById('toChange').src='https://www.youtube.com/embed/LINK2';
document.getElementById('__2__').id="active";
 }

 function changeto3(){
document.getElementById('toChange').src='https://www.youtube.com/embed/LINK3';
document.getElementById('__3__').id="active";
 }
</script>

它可以工作但是,我需要重置之后的功能。因为当我点击视频1时,如果我点击视频2,它将获得id="active",因此它们具有相同的ID。 :)

我需要重置它们,例如,如果我点击Video 2 id=active并重置其他所有内容......任何其他想法都会对我有所帮助。 感谢。

1 个答案:

答案 0 :(得分:0)

根据@ yuriy636的建议,您不应更改id代码的<a>值,而应该使用其类名值。

<html>

    <head>
        <script>
    function change(id) {
        var src = "";
        switch (id) {
            case 1:
                src = 'https://www.youtube.com/embed/LINK1';
                break;
            case 2:
                src = 'https://www.youtube.com/embed/LINK2';
                break;
            case 3:
                src = 'https://www.youtube.com/embed/LINK3';
                break;
            default:
                // For debug. But you should handle it.
                console.log("Error!");
        }
        document.getElementById('toChange').src = src;

        //All the <a> are no longer active.
        var as = document.getElementsByName('link');
        for (var i = 0; i < as.length; i++)
            as[i].className = "notActive";

        //The clicked is active now.
        document.getElementById(id).className = "active";
    }

    </script>
    </head>

    <body>
        <iframe id="toChange" width="560" height="315" src="https://www.youtube.com/embed/FirstLink" frameborder="0" allowfullscreen></iframe>

        <a id="1" name="link" onclick="change(1)">Video 1</a>
        <a id="2" name="link" onclick="change(2)">Video 2</a>
        <a id="3" name="link" onclick="change(3)">Video 3</a>
    </body>

    </html>

这是fiddle。 我创建了一个函数,通过使用每个元素的id可以改变它的类而不是几个函数。