简体   繁体   English

如何从 Javascript 中的 html 标签中检索信息?

[英]How can i retrieve informations from html tags in Javascript?

I am trying to pull certain item IDs based on if they have an image tag or not.我试图根据它们是否有图像标签来提取某些项目 ID。 For a given input like the one below:对于给定的输入,如下所示:

<div id="ID_1">
     <p><img src="image4.png"></p>
</div>

<div id="ID_2">
</div>

<div id="ID_3">
     <p><img src="image6.png"></p>
</div>

<div id="ID_4">
     <p><img src="image4.png"></p>
</div>

I could get something like:我可以得到类似的东西:

ID_1: image4.png
ID_2:
ID_3: image6.png
ID_4: image4.png

I am not too familiar with HTML or Javascript, so any help or resources that someone may have or know will be greatly appreciated.我对 HTML 或 Javascript 不太熟悉,因此将不胜感激任何人可能拥有或知道的任何帮助或资源。

I would recommend using jQuery for something like this (dont forget to include jquery in the html head)我建议将 jQuery 用于这样的事情(不要忘记在 html 头中包含 jquery)

Html => html =>

<div id="divContainer" >
<div id="ID_1">
     <p><img src="image4.png"></p>
</div>

<div id="ID_2">
</div>

<div id="ID_3">
     <p><img src="image6.png"></p>
</div>

<div id="ID_4">
     <p><img src="image4.png"></p>
</div>
</div>

Javascript => Javascript =>

const doesContainImg = [];

$(".divContainer div").each(function() {
    // check for an img 
    if ($(this).find("img").length) {
      // store id in array that contains ids that have imgs
      doesContainImg.push($(this).attr("id"));
   }
});

that should work, if it does not let me know!这应该有效,如果它不让我知道!

Add a class on those div.在这些 div 上添加一个类。 Let's say you have the class "image-div".假设您有“image-div”类。

We can use this class to see if the divs contain an image or not.我们可以使用这个类来查看 div 是否包含图像。

JQUERY:查询:

$(".image-div").each(function(){
    if($(this).find('img').length){
       //if this div contains an image do something.
    }
});

You can attach this code to an event and use it您可以将此代码附加到事件并使用它

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

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