Javascript无法识别函数中的变量
我正在尝试创建一个脚本,它可以通过单击链接来打开和关闭图像进行练习。我试图选择一个“data-”属性,但当我试图将它定义为一个变量时,它无法识别它。它给了我一个空错误 这是我的HTML:Javascript无法识别函数中的变量,javascript,Javascript,我正在尝试创建一个脚本,它可以通过单击链接来打开和关闭图像进行练习。我试图选择一个“data-”属性,但当我试图将它定义为一个变量时,它无法识别它。它给了我一个空错误 这是我的HTML: <a data-img="image1" id="ugur1" class="btn btn-default" href="#" role="button">Toggle Image one</a> <a data-img="image2" id="ugur2" class="bt
<a data-img="image1" id="ugur1" class="btn btn-default" href="#" role="button">Toggle Image one</a>
<a data-img="image2" id="ugur2" class="btn btn-default" href="#" role="button">Toggle Image two</a>
<a data-img="image3" id="ugur3" class="btn btn-default" href="#" role="button">Toggle Image three</a>
<img src="C:\Users\Ugur Aydin\Desktop\Coding\Javascript\Images\Image1.png" class="img-responsive img hide" id="ugurpic1" alt="Responsive image" />
<img src="C:\Users\Ugur Aydin\Desktop\Coding\Javascript\Images\Image2.png" class="img-responsive img hide" id="ugurpic2" />
<img src="C:\Users\Ugur Aydin\Desktop\Coding\Javascript\Images\Image3.png" class="img-responsive img hide" id="ugurpic3" />
有人能告诉我我做错了什么吗?谢谢。您正在使用
getElementById
正确地选择每个a
,并正确地添加事件侦听器。问题是,当您选择数据img
属性时,它们不包含图像的ID。基本上,每次将data img=“imageX”
更改为data img=“ugurpicX”
以正确反映图像标签的ID,或更改图像标签的ID
任一
<a data-img="ugurpic1" id="ugur1" class="btn btn-default" href="#" role="button">Toggle Image one</a>
<a data-img="ugurpic2" id="ugur2" class="btn btn-default" href="#" role="button">Toggle Image two</a>
<a data-img="ugurpic3" id="ugur3" class="btn btn-default" href="#" role="button">Toggle Image three</a>
或(不是两者都有):
尝试使用document.getElementById(“ugurpic1”)而不是document.getElementById(“ugur1”)?并可能添加一些实际的数据属性?如果您选中此项,您会发现您没有任何数据img
属性。您认为这很有效!我也从中吸取了教训!因此,我知道给定给data属性的id必须与给定给我试图操作的图像的id相同。再次感谢你!
<a data-img="ugurpic1" id="ugur1" class="btn btn-default" href="#" role="button">Toggle Image one</a>
<a data-img="ugurpic2" id="ugur2" class="btn btn-default" href="#" role="button">Toggle Image two</a>
<a data-img="ugurpic3" id="ugur3" class="btn btn-default" href="#" role="button">Toggle Image three</a>
<img src="C:\Users\Ugur Aydin\Desktop\Coding\Javascript\Images\Image1.png" class="img-responsive img hide" id="image1" alt="Responsive image" />
<img src="C:\Users\Ugur Aydin\Desktop\Coding\Javascript\Images\Image2.png" class="img-responsive img hide" id="image2" />
<img src="C:\Users\Ugur Aydin\Desktop\Coding\Javascript\Images\Image3.png" class="img-responsive img hide" id="image3" />