单击时切换图像时添加文本

时间:2018-05-02 11:17:07

标签: javascript html

我正在使用此JSFiddle来切换图片。我需要为每个添加不同的标题文本,如下图所示,我想必须有一种方法可以在脚本上添加此文本。

<script>
    function change() {
   var img1 = "http://placehold.it/350x150",
       img2 = "http://placehold.it/200x200";
   var imgElement = document.getElementById('test');
   
   imgElement.src = (imgElement.src === img1)? img2 : img1;
}
</script>
<img src="http://placehold.it/350x150" id="test" onclick ="change();"/>

enter image description here

2 个答案:

答案 0 :(得分:0)

正如我在评论中提到的,如果您的图片下方有span,则可以像切换图片一样切换文字。

&#13;
&#13;
<script>
    function change() {
   var img1 = "http://placehold.it/350x150",
       img2 = "http://placehold.it/200x200",
       img1Text = 'Image 1 Text',
       img2Text = 'Image 2 Text';
       
   var imgElement = document.getElementById('test'),
       imgTextElement = document.getElementById('testText');
   
   imgElement.src = (imgElement.src === img1)? img2 : img1;
   imgTextElement.innerText = (imgTextElement.innerText === img1Text)? img2Text: img1Text;
}
</script>
<img src="http://placehold.it/350x150" id="test" onclick ="change();"/>
<span style="display: block" id='testText'>Image 1 Text</span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

function change() {
   var img1 = "http://placehold.it/350x150",
       img2 = "http://placehold.it/200x200";
   var imgElement = document.getElementById('test');
   
   imgElement.src = (imgElement.src === img1)? img2 : img1;
   document.getElementById("test-span").innerHTML = (imgElement.src === img1)? "img2" : "img1";
}
div{
 display:flex;
}
<div><img src="http://placehold.it/350x150" id="test" onclick ="change();"/>
<span id="test-span">img1</span>
</div>