jQuery onclick create and endend element with 属性和子项



我有一个页面,其中有许多指向不同视频文件的anchors和一个div

<a href="http://www.example.com/example-1.mp4" class="video">1</a>
<a href="http://www.example.com/example-2.mp4" class="video">2</a>
<a href="http://www.example.com/example-3.mp4" class="video">3</a>
<div id="video-player">
</div>

当用户单击链接时,我希望在div内创建一个video元素,如下所示:

<div id="video-player">
<video>
<source src="[HREF-FROM-THE-A]">
</video>
</div>

我需要video元素上的controlsautoplay属性。

我需要向定位点添加类吗?我是这么想的...因为我在页面上还有其他链接不是视频。更新了问题。

这对某人来说应该很容易,我对 JS/jquery 很糟糕。我尝试搜索:"jquery create element onclick","jquery append element onclick"。

您可以收听<a>上的点击,并使用html方法注入所需的视频标签。可以使用 jquery 的attr方法获取href值,并结合单击<a>$(this)

$("a.video").click(function(event){
event.preventDefault();
$("#video-player").html("<video controls src=" + $(this).attr("href") + "></video>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.example.com/example-1.mp4">1</a>
<a href="http://www.example.com/example-2.mp4">2</a>
<a href="http://www.example.com/example-3.mp4">3</a>
<div id="video-player">
</div>

我还在生成的<video>上添加了controls,以便更清楚地创建它。

将锚标记替换为:

<a href="javascript:void(0);" class="video" onclick="addvideo('http://www.example.com/example-1.mp4')">1</a>
<a href="javascript:void(0);" class="video" onclick="addvideo('http://www.example.com/example-2.mp4')">2</a>
<a href="javascript:void(0);" class="video" onclick="addvideo('http://www.example.com/example-3.mp4')">3</a>

然后添加一个 JavaScript 函数:

function addvideo(href)
{
$('#video-player').html('<video controls autoplay><source src="'+href+'"></video>');
}

最新更新