微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何将图像源作为字符串返回?

我正在尝试将图像源转换为字符串,以便我可以在其上运行substring().我使用以下JavaScript获取代码

function ShowQuizAnswers(quiz) {
    var QuizImage = document.getElementById(quiz);
    var ImageType = QuizImage.attributes.src;
    console.log(ImageType);
}

当然,正如我很快发现的那样,这返回了一个对象而不是一个字符串.我尝试在ImageType变量上运行.toString(),但这不起作用.有什么我想念的吗?

最佳答案
使用Element#getAttribute或直接从dom对象获取src属性.

function ShowQuizAnswers(quiz) {
    var QuizImage = document.getElementById(quiz);
    var ImageType = QuizImage.src;
    console.log(ImageType);
}

要么

function ShowQuizAnswers(quiz) {
    var QuizImage = document.getElementById(quiz);
    var ImageType = QuizImage.getAttribute('src');
    console.log(ImageType);
}

仅供参考:attributes是类似阵列的结构(NamedNodeMap).它实际上有助于迭代元素的所有属性,但是您无法直接从它访问属性.

来自MDN文档:

The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. It is a 07003,not an Array,so it has no Array methods and the Attr nodes’ indexes may differ among browsers. To be more specific,attributes is a key/value pair of strings that represents any information regarding that attribute.

原文地址:https://www.jb51.cc/js/429300.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐