简体   繁体   English

使用document.write时,元素在inspect元素中不显示

[英]Element doesn't show in inspect element when using document.write

I wrote the following JS code: 我写了以下JS代码:

<script>
function myFunction() {
  document.write("<img src=x>")
}
myFunction();
</script>

while my function works fine and adds a new img tag to the page whenever I use Ctrl+Shift+I in Chrome then Ctrl+F then I type <img src=x> and I get 0 of 0 found . 虽然我的功能正常工作,每当我在Chrome中使用Ctrl + Shift + I然后按Ctrl + F然后输入<img src=x>然后我找到0 of 0 found我会在页面上添加一个新的img标签。 How to fix this? 如何解决这个问题?

From your comment: 来自你的评论:

ctrl+shift+i in chrome then ctrl+F then I type and I get 0 of 0 found ctrl + shift + i在chrome然后ctrl + F然后我输入,我得到0的0

There's no need to do that. 没有必要这样做。 Just right-click the image and click Inspect. 只需右键单击该图像,然后单击“检查”。 Chrome will take you right to it in the Elements panel. Chrome会在“元素”面板中将您带到右侧。

Re searching in the Elements panel: 在“元素”面板中重新搜索:

The Elements panel doesn't show the exact HTML you wrote, it shows you the DOM, rendered as canonical HTML. “元素”面板不显示您编写的确切HTML,它显示DOM,呈现为规范HTML。 So for instance, the src attribute will be in quotes. 因此,例如, src属性将在引号中。

But , the search box in the Elements panel doesn't search HTML , it searches the DOM. 但是 ,“元素”面板中的搜索框不会搜索HTML ,而是搜索DOM。 So typing plain text will match text in text in text nodes, text in attributes, attribute names, tag names, etc., but not exact HTML. 因此,输入纯文本将匹配文本节点中的文本,属性中的文本,属性名称,标签名称等,但不是精确的HTML。 So if you search for the URL of the image, it'll find it, but it won't find it if you search for <img src= . 因此,如果您搜索图像的URL,它会找到它,但如果您搜索<img src= ,则无法找到它。 This has nothing to do with it having been added via document.write , it's just how Chrome's Elements panel works. 这与通过document.write添加它无关,它只是Chrome的Elements面板的工作方式。

You can find the element by typing XPath or a CSS selector, for instance img[src=x] will find it. 您可以通过键入XPath或CSS选择器来找到该元素,例如img[src=x]会找到它。 Here's an example (I used your Gravatar rather than x ): 这是一个例子(我用你的Gravatar而不是x ):

在元素面板中使用搜索的示例

There, you can see that the selector img[src*=gravatar] found the image, because that selector (using the "contains" attribute selector, *= ) matches the element. 在那里,你可以看到选择器img[src*=gravatar]找到了图像,因为该选择器(使用“contains”属性选择器, *= )与元素匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM