繁体   English   中英

在div中选择图像

[英]Selecting an image inside a div

<div>
    <div id ="container">
       <div>
           <img src="some src>
       </div>
       <p>get this text</p>
       <h>hello</h>
     </div>
</div>

我想要主div内的图像总数,并要提取除图像标签以外的html标签。
OUTPUT:
图片数量= 1
strings = <p>get this text</p><h>hello</h>

请给我一个演示

尝试这个

$('#container').find('img').length

$("#container img").length用于img标签计数

要为每个字符串提取字符串,

$("#container").find("p, h").not("div").each(function() {
    console.log($(this).get(0)); //Object
});

注意:您正在使用一些奇怪的<h>元素,它是无效的HTML标记,我认为它是<h1>或其他一些标头元素。

演示: http : //jsbin.com/nosin/5/edit

JS:

var a = $('#container').find('img').length;

console.log('No. of images =' + a);

var b = $('#container').find('h1, h2, h3, h4, h5, h6, p');
var c = '';

for(var i = 0; i < b.length; i++) {
  c += b[i].outerHTML;
}

console.log('strings=' + c);

HTML:

<div>
  <div id ="container">
     <div>
       <img src="some src"/>
     </div>
     <p>get this text</p>
     <h1>hello</h1>
   </div>
</div>

OUTPUT:

"No. of images =1"
"strings=<p>get this text</p><h1>hello</h1>"

请选中此选项,它将对您有所帮助。

$(document).on("click", "#container", function(){
    var img = $(this).find("img"), // select images inside container
        len = img.length; // check if they exist
    if( len > 0 ){
        // images found, get id
        var attrID = img.first().attr("src"); // get src attr of first image
    } else {
        // images not found
    }
});
//For multiple images
var arr = []; // create array
if( len > 0 ){
    // images found, get src
    img.each(function(){ // run this for each image
        arr.push( $(this).attr("src") ); // push each image's src to the array
    });
} else {
    // images not found
}
   Try this :

   <script type="text/javascript">
   $(document).ready(function(){
    var no_of_img = jQuery('#container img').length;
    $("#container").find("*").each(function() {
      var obj = $(this).get(0); //Object
      if($(obj).find("img").length > 0 || $(obj).is("img")){

      }else{
        console.log($(obj).get(0));
      }
    });
   });
  </script>

暂无
暂无

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

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