如何在页面加载时动态更改href内容

时间:2018-06-25 07:40:25

标签: javascript jquery jquery-plugins flowplayer

我想在Web浏览器上运行mp4视频。为此,我正在使用流播放器,并且我想在页面加载时动态更改href内容。我已经使用了下面的代码。

<html><head>
<title>Wow! This is video</title>

<script src="http://releases.flowplayer.org/js/flowplayer-3.2.13.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {
        //var Filename = document.getElementById("<%=hdnFileName.ClientID%>").value;
        var Filename = "http://www.yahoo.com";

        $("a.mylink").attr("href", Filename);
    });
</script></head><body>


<!-- <a href="Video/Test.mp4" style="width: 500px; height: 400px;" id="A"></a>-->
<a href="Video/Test.mp4" style="width: 500px; height: 400px; margin: 10px; display: block" class="Test1" id="Test1"></a>
<script language="JavaScript" type="text/javascript">
    flowplayer("Test1", "http://releases.flowplayer.org/swf/flowplayer-3.2.18.swf");
</script></body></html>

在这里,我将从外部传递锚标记值,我想将其设置为锚标记。 但是上面的代码是行不通的。你能帮忙吗?

2 个答案:

答案 0 :(得分:0)

我知道有两种方法可以实现您想要的

第一:不要将href属性设置为HTML中的任何内容,然后使用js进行设置

HTML代码:

<a style="width: 500px; height: 400px; margin: 10px; display: block" class="Test1" id="Test1"></a>

JS代码:

document.getElementById("Test1").setAttribute("href", Filename);

2nd:创建一个新的Tag并将其替换为

JS代码:

var Filename = "http://www.yahoo.com";
var aTag = document.createElement("a");
aTag.style.width = "500px";
aTag.style.height = "400px";
aTag.style.display = "block";
aTag.classList.add("Test1");
aTag.setAttribute("href", Filename);
aTag.id = "Test1";
document.getElementById("Test1").replaceWith(aTag)

答案 1 :(得分:0)

工作代码:

<html>
<head>
<title>Wow! This is video</title>

<script src="http://releases.flowplayer.org/js/flowplayer-3.2.13.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

</head><body>


<!-- <a href="Video/Test.mp4" style="width: 500px; height: 400px;" id="A"></a>-->
<a href="Test.mp4" style="width: 500px; height: 400px; margin: 10px; display: block" class="Test1" id="Test1"></a>
<script language="JavaScript" type="text/javascript">
  file = "http://techslides.com/demos/sample-videos/small.mp4";//any sample file you want
  $("a").attr("href",file);
  flowplayer("Test1", "http://releases.flowplayer.org/swf/flowplayer-3.2.18.swf"); 
</script></body></html>

您可能想知道为什么这行得通而不是您的。所以这就是原因。

您正在做的两个大错误:

  1. mylink?它无处。如果使用更好 $(“#Test1”) 要么 $(“。Test1”)

  2. 文档准备就绪后,您正在加载脚本。这意味着,如果您调试代码或查看页面源,您会发现您的href已更新,但仅播放旧视频。 要更正它,您需要设置没有ready函数的属性。 仍然不起作用,因为如果您将其写在顶部,它将被实际的href属性覆盖。

  3. Yahoo.com不是mp4视频。您提供的属性确保是视频。