【问题标题】:Getting the href attribute of an image with Javascript使用 Javascript 获取图像的 href 属性
【发布时间】:2011-09-21 02:04:49
【问题描述】:

Javascript 新手,真的需要帮助!

现在我在 HTML 页面中有一个图像,如下所示:

<a class="p" href="http://www.abc.com"><img src="http://www.abc.com/logo.jpg" alt="" /></a>

并通过以下方式获取图像元素:

var e.document.elementFromPoint(x,y);

点击图片时,可以通过以下方式成功获取src属性或offset属性:

e.src or e.offsetHeight

但是,当我使用它时它返回 NULL:

return e.href;

那么我怎样才能获得正确的 href 属性(http://www.abc.com)??

谢谢,

高峰

【问题讨论】:

    标签: javascript html ios href src


    【解决方案1】:

    href 不是图像的属性,而是 A 元素的属性。

    您可以使用图像的.parentNode 属性来访问它。因为它是它的直接父级。

    【讨论】:

      【解决方案2】:

      使用parentNode可以得到img的父节点,也就是a

      return e.parentNode.href;
      

      【讨论】:

        【解决方案3】:

        href 属性仅适用于 alink 元素。所以只需要获取图片的父节点即可:

        var thea=e.parentNode;
        if(thea.nodeName.toLowerCase()=="a"){ //If the tag is a hyperlink
            return thea.href;
        }else{
            return ""; //Return an empty string if the image is not inside a hyperlink
        }
        

        广告@m

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-07
          • 1970-01-01
          • 1970-01-01
          • 2010-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多