簡體   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