Javascript onclick更改图像标题

时间:2014-10-16 13:58:15

标签: javascript variables

我需要在播放器下显示当前加载的视频的标题。用户登录缩略图以在jwplayer上加载视频。我只能加载第一个标题。



<div>Now playing: <span id='nowPlaying'>My 40th Aniversary</span> </div>


<script type="text/javascript">
function changeTitle(){
	  var video = document.getElementById('vidTitle').getAttribute('title');
	  document.getElementById('nowPlaying').innerHTML = video;
}
</script>

<!-- body of my pge -->

<h2>Trips</h2>
<ul>
  <li> <a href="javascript:loadVideo('rtmp://OnDemand/triptoElgin.mp4');"> <img   src="http://www.example.com/images/triptoelgin.jpg"  id='vidTitle' onclick='changeTitle()' title="Trip to Elgin "/></a>Trip to Elgin</li>

<li> <a href="javascript:loadVideo('rtmp://OnDemand/triptoWaco.mp4');"> <img  src="http://www.example.com/images/triptowaco.jpg"  id='vidTitle' onclick='changeTitle()' title="Trip to Waco"/></a>Trip to Waco</li>
</ul>

<!-- begin snippet: js hide: false -->
&#13;
&#13;
&#13;

如何添加变量以加载下一个视频标题?我尝试过这个,但它给出了未定义的值。

3 个答案:

答案 0 :(得分:2)

在HTML中,id属性必须是唯一的。现在,当您拨打document.getElementById('vidTitle')时,无论如何,浏览器都会选择第一个。如果您要确定自己点击了哪些图片,我会将this发送到changeTitle功能,如下所示:

的JavaScript

function changeTitle(element){
  var video = element.getAttribute('title');
  document.getElementById('nowPlaying').innerHTML = video;
}

HTML

<ul>
  <li> <a href="javascript:loadVideo('rtmp://OnDemand/triptoElgin.mp4');"><img src="http://www.example.com/images/triptoelgin.jpg" id='vidTitle1' onclick='changeTitle(this)' title="Trip to Elgin "/></a>Trip to Elgin</li>
  <li> <a href="javascript:loadVideo('rtmp://OnDemand/triptoWaco.mp4');"> <img src="http://www.example.com/images/triptowaco.jpg"  id='vidTitle2' onclick='changeTitle(this)' title="Trip to Waco"/></a>Trip to Waco</li>
</ul>

答案 1 :(得分:1)

    function changeTitle(element){
  var video = element.getAttribute('title');
  document.getElementById('nowPlaying').innerHTML = video;
}

答案 2 :(得分:0)

<div>Now playing: <span id='nowPlaying'>My 40th Aniversary</span> </div>


<script type="text/javascript">
function changeTitle(video){
	  var video = video.getAttribute('title');
	  document.getElementById('nowPlaying').innerHTML = video;
}
</script>

<!-- body of my pge -->

<h2>Trips</h2>
<ul>
  <li> <a href="javascript:loadVideo('rtmp://OnDemand/triptoElgin.mp4');"> <img   src="http://www.example.com/images/triptoelgin.jpg" onclick='changeTitle(this)' title="Trip to Elgin "/></a>Trip to Elgin</li>

<li> <a href="javascript:loadVideo('rtmp://OnDemand/triptoWaco.mp4');"> <img  src="http://www.example.com/images/triptowaco.jpg" onclick='changeTitle(this)' title="Trip to Waco"/></a>Trip to Waco</li>
</ul>

<!-- begin snippet: js hide: false -->