【问题标题】:how to run identical javascript functions如何运行相同的javascript函数
【发布时间】:2011-12-03 18:13:24
【问题描述】:

经过广泛的研究,我找不到适合我(相当)低技能的 javascript 的答案。如果你们中的任何人能提供帮助,那将是一个很大的解脱。

我试图在同一页面上运行此脚本两次,但我认为问题在于不能调用 onYouTubePlayerReady 函数两次而不会被最后一次覆盖。 此外,如果我更改它的名称,则不会执行实际功能。

这是代码。我希望它可以在同一页面中播放多达 4 个没有声音和自动播放的 youtube 视频。你知道怎么可能吗?

感谢您的宝贵时间

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Prova 1</title>

<script src="http://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
      google.load("swfobject", "2.1");
    </script> 

</head>

<body align="center">


<div id="ytapiplayer2"></div>

    <script type="text/javascript">
        function onYouTubePlayerReady2(playerId2) {
            ytplayer2 = document.getElementById("myytplayer2");
            ytplayer2.playVideo();
            ytplayer2.mute();
                }
        var videoID2 = "OFIhzSwDfwo"
        var params = { allowScriptAccess: "always" };
        var atts = { id: "myytplayer2" };
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID2 + "?enablejsapi=1&playerapiid=ytplayer\
        &autoplay=1&version=3&showinfo=0&iv_load_policy=3&controls=0&modestbranding=1",
        "ytapiplayer2", "250", "inherit", "0", null, null, params, atts)
    </script>



<div id="ytapiplayer"></div>

    <script type="text/javascript">
        function onYouTubePlayerReady(playerId) {
            ytplayer = document.getElementById("myytplayer");
            ytplayer.playVideo();
            ytplayer.mute();
                }
        var videoID = "e5iqtQLm-BM"
        var params = { allowScriptAccess: "always" };
        var atts = { id: "myytplayer" };
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "?enablejsapi=1&playerapiid=ytplayer\
        &autoplay=1&version=3&showinfo=0&iv_load_policy=3&controls=0&modestbranding=1",
        "ytapiplayer", "250", "inherit", "0", null, null, params, atts)
    </script>


</body>
</html>

【问题讨论】:

  • 我看到了一些可能有问题的事情,例如ytplayer 是全局的,不是函数本地的。此外,您使函数接受一个参数,但它没有使用它。你有两段相同的代码。你是说两者都用不了?或者您对两个视频都使用原始onYouTubePlayerReady 功能有问题吗?
  • 嗨,菲利克斯,我应该让他们在本地解决吗?
  • 我不知道,正如我所说,似乎有几个问题。例如。您没有 ID 为 myytplayer2myytplayer 的元素。 onYouTubePlayerReady2 永远不会被调用,因为 API 不知道这个函数。
  • 第二个脚本可以同时使用它们
  • 我可以看到具有这些 myytplayer Id 的嵌入元素,如果无法识别 onYouTubePlayerReady2,我该如何为这两个元素(嵌入视频)运行它?

标签: javascript algorithm function optimization name-collision


【解决方案1】:

使用参数而不是全局变量来避免副作用:

 function onYouTubePlayerReady2(playerId2, ytplayer2, video2, params, atts)

然后传入硬编码的值,而不是在每次调用期间更改状态。

【讨论】:

    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多