我正在尝试将图像源转换为字符串,以便我可以在其上运行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.