如何从html文件中的li标签调用get属性

How to call get attribute from a li tag in html file

本文关键字:标签 li 调用 get 属性 html 文件      更新时间:2023-09-26

我想做的与此类似。

当我点击"电影A"时,我希望函数$('#playlist li').click(function(){...})会被调用,但似乎什么都没有发生。有什么问题吗?

index . html:

<!DOCTYPE html>
<html>
<head>
  <title>Home Video Player</title>
</head>
<body>      
    <video id="video" width="640" height="320" controls="controls">
        Your browser does not support the video tag.
    </video>    
    <ul id="playlist">
        <li movieurl="a,mp4" movietype="video/mp4">Movie A</li>
        <li movieurl="b.mp4" movietype="video/mp4">Movie B</li>          
        <li movieurl="c.mp4" movietype="video/mp4">Movie C</li>      
        <li movieurl="d.mp4" movietype="video/mp4">Movie D</li>
    </ul>       
    <script src="main.js"> </script>
</body>
</html>

main.js

$(document).ready(function(){
    $('#playlist li').click(function(){
        var video = document.getElementById('video');
        var source = document.createElement('source');
        source.setAttribute('src', $(this).attr("movieurl"));
        source.setAttribute('type', $(this).attr("movietype"));
        video.appendChild(source);
    });
});

如果你要使用Jquery,你需要链接它,这里是CDN链接。

   <script language="javascript" type="text/javascript"   src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

您没有引用JQuery。

您很可能会在控制台(例如Firebug)中看到"$未定义"..这意味着还没有创建JQuery "$"对象。

要解决这个问题,包括对JQuery的引用(本地或CDN)

<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<script language="javascript" type="text/javascript" src="jquery-1.11.3.min.js"></script>

应该做你需要它做的事。

请记住,JQuery必须在脚本之前定义:

<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script language="javascript" type="text/javascript" src="main.js"> </script>

您可以从https://code.jquery.com/jquery/

获得正确版本的JQuery。

另外,正如其他人注意到的:

  • movie,a应该是movie。项目列表中的a
  • 你可以使用$('#elementid')来获取元素,而不是在JQuery中使用getElementById -输入要短得多!

添加到你的html <head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

将以下代码放在<head>标签之间:

<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script language="javascript" type="text/javascript" src="main.js"></script>

为了使用jQuery和javascript文件,你需要告诉你的html文档,有一些JS文件可以解释页面的行为。

同样,因为你正在使用jQuery,你可以替换

document.getElementById('video');

$('#video');

编辑:我更正,脚本的最佳实践是将它们添加到body的末尾。