Javascript 获取 img.src 值(路径名)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10843322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:11:59  来源:igfitidea点击:

Getting img.src value (path name)

javascripthtmlforms

提问by Jamie Stuart Robin Parsons

I have a form for a registration page. The form contains an image that changes its src dependant on a situation. Within a script which activates upon submission of the form, I want the form to call an alert if that image has a particular src, so I need a way of retrieving and comparing the value.

我有一个注册页面的表格。该表单包含一个图像,该图像根据情况更改其 src。在提交表单时激活的脚本中,如果该图像具有特定的 src,我希望表单调用警报,因此我需要一种检索和比较值的方法。

HTML:

HTML:

<form action="register_submit.php" method="post" name="mainform" enctype="multipart/form-data" onSubmit="return checkForm(this);return false;">

JS:

JS:

    function checkForm(f)
    {if ([image src value] == "pictures/apic.png")
       {
          alert("error picture is apic");
          return false;
       }
     else
       {
          f.submit();
          return false;
       }
    }

Here is the relative code in full:

这是完整的相关代码:

    <script type="text/javascript">
            function checkForm(f)
            {if ([image src value] == "pictures/apic.png")
               {
                  alert("error picture is apic");
                  return false;
               }
             else
               {
                  f.submit();
                  return false;
               }
            }
    </script>

    <form action="register_submit.php" method="post" name="mainform" enctype="multipart/form-data" onSubmit="return checkForm(this);return false;">

    <div class="required">
    <label for="first_name">*First Name:</label>
    <input type="text" name="first_name" id="first_name" class="inputText" onkeyup="checkFName(this.value);" onblur="checkFName(this.value);" maxlength="20" size="10" value="" />
    <img id="FName_Status" name="FName_Status" src="/pictures/bad.png" style="margin-left:5px; position:absolute;" alt="FName_Status" />
    </div>

    (OTHER OBJECTS)
    </form>

<input type="submit"  name="sub" class="inputSubmit" value="Submit &raquo;"/>

回答by Danilo Valente

Use this:

用这个:

if (document.getElementById('FName_Status').getAttribute('src') == "pictures/apic.png")

回答by Mike Chamberlain

Add an ID tag to your image (if it doesn't already have one), eg:

为您的图像添加一个 ID 标签(如果它还没有),例如:

<img src="pictures/apic.png" id="imageId" />

Then you can reference it as follows:

然后你可以参考它如下:

if (document.getElementById("imageId").src == "pictures/apic.png")
{
    ...
}

EDIT

编辑

Working example here: http://jsfiddle.net/2Wtkn/2/

这里的工作示例:http: //jsfiddle.net/2Wtkn/2/