从 Javascript 中的图像获取名称

Get name from image in Javascript

我有几张图片可以点击。
单击图像时,我应该在文本字段中添加名称。
所以在这个例子中,一个米老鼠的图像,图像的名称是"Mickey Mouse",这个名称应该在文本字段中。
使用我的代码,整个图像字符串都在文本框中。

这是图片

<a onClick="insertText(this)" 
   href="#pagetwo" 
   data-transition="slide">
       <img src="images/mickey.png" 
            name="Mickey Mouse" 
            width="114" 
            height="114">
</a>

写入文本字段的函数:

function insertText(txt) {
    document.getElementById('disney').value = txt.innerHTML;
}

表单域:

<label for="name">Melding:</label>
<input type="text" name="disneyfigure" 
       id="disney" readonly 
       value="<hier komt automatisch disney figuur>">

您需要在 div 中找到 img,使用 querySelector or getElementsByTagName, then get it's name attribute using getAttribute():

function insertText(txt)
{
    var image = txt.getElementsByTagName('img')[0]; // find the image
    var text = image.getAttribute('name'); // get it's name attribute value
    document.getElementById('disney').value = text;
}
<div><a onClick="insertText(this)" href="#pagetwo" data-transition="slide"><img src="images/mickey.png" name="Mickey Mouse" width="114" height="114"></a></div>

<label for="name">Melding:</label>
<input type="text" name="disneyfigure" id="disney" readonly value="<hier komt automatisch disney figuur>">

insertText(this)中的this指的是锚标签。因此,当您请求时,innerHTML 它会提供锚标记中包含的 html。

另外,由于需要提取name属性,所以必须专门取回这个属性。

将函数更改为

function insertText(a) {
    document.getElementById('disney').value = a.getElementsByTagName('img')[0].getAttribute('name');
}

您应该使用 alt 属性作为图像名称。

<img src="images/mickey.png" alt="Mickey Mouse" width="114" height="114">

然后您可以使用以下代码轻松将其填充到输入文本中:

document.getElementById('disney').value = txt.alt;