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.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...