[英]Why does assigning a variable to itself in a Dom Object make a difference
I have a HTML String, called tinymceToHTML in my example and I had the problem that when I download this html String the images sources or hrefs were set wrongly. 我有一个HTML字符串,在我的例子中名为tinymceToHTML,我遇到的问题是,当我下载这个html字符串时,图像源或href设置错误。
My image sources looked like "/file/:id" in the original String, if I convert it into a DOM object and output the source it looks like " http://localhost:3000/file:id " which is the desired output, because then the external document can load this file. 我的图像源在原始String中看起来像“/ file /:id”,如果我将其转换为DOM对象并输出它看起来像“ http:// localhost:3000 / file:id ”的源,这是所需的输出,因为那时外部文件可以加载这个文件。 So I came up with this solution. 所以我提出了这个解决方案。
var div = document.createElement('div'); div.innerHTML = tinymceToHTML; var images = div.getElementsByTagName('img'); for(var i = 0; i < images.length; i++) { images[i].src = images[i].src; } var a = div.getElementsByTagName('a'); for(var i = 0; i < a.length; i++) { a[i].href = a[i].href; } tinymceToHTML = "<html><head></head><body>" + div.innerHTML + "</body></html>";
My problem is that I don't know why assigning the variable to itself makes a difference in that scenario: images[i].src = images[i].src or a[i].href = a[i].href. 我的问题是,我不知道为什么将变量赋给自身在这种情况下有所不同:images [i] .src = images [i] .src或a [i] .href = a [i] .href。
If I let the program show me the output with an alarm Box it tells me the URL I want, but without that assignment the program doesn't do what it should. 如果我让程序向我显示带有警报框的输出,它会告诉我我想要的URL,但如果没有这个分配,程序就不会做它应该做的事情。
I hope that anybody can explain me that effect, in order to change maybe the code to make it more clear that this line is required. 我希望任何人都可以向我解释这种效果,以便更改代码,以便更清楚地说明这一行是必需的。
I also created a fiddle example that makes it easier to show what I mean, comment out the line with the assignment, to see the other result 我还创建了一个小提琴示例,可以更容易地显示我的意思,注释掉分配的行,以查看其他结果
https://jsfiddle.net/1vabgubh/5/ https://jsfiddle.net/1vabgubh/5/
The full URL of an image is just what imageElement.src returns, by definition. 根据定义,图像的完整URL正是imageElement.src返回的内容。 From MDN : 来自MDN :
HTMLImageElement.src Is a DOMString that reflects the src HTML attribute, containing the full URL of the image including base URI. HTMLImageElement.src是一个反映src HTML属性的DOMString,包含图像的完整URL,包括基URI。
If that's how you need them to come out in your final string, then images[i].src = images[i].src
seems a reasonable and succinct way of doing it. 如果你需要它们在你的最终字符串中出现,那么images[i].src = images[i].src
似乎是一种合理而简洁的方式。 I would just add a comment to aid understanding, something like 我只想添加评论以帮助理解,例如
images[i].src = images[i].src; // force the src to be the full URI
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.