2017-06-14 28 views
0

我刮網頁提取與特定CSSselector了這樣的內容:

$("p, h1, h2").each(function(index) { 
    // Do stuff 
}) 

現在,我想要知道什麼選擇器對應於返回的對象:我想知道它是p標記,h1標記還是h2標記。

我該如何做到這一點?這裏的理念是:

$("p, h1, h2").each(function(index) { 
    console.log("CSS Selector: ", $(this).cssSelectorName) 
}) 
+0

看看[TagName屬性(https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName),例如'this.tagName' –

回答

3

按照documentation你可以寫:

$("p, h1, h2").each(function(index, ele) { 
    console.log("CSS Selector: ", ele.tagName); 
}) 

一種不同的方法可以根據.is()

$("p, h1, h2").each(function(index, ele) { 
 
    console.log("CSS Selector: ", ele.tagName.toLowerCase()); 
 
    if ($(ele).is('p')) { 
 
     console.log('This is a paragraph') 
 
    } else { 
 
     if ($(ele).is('h1')) { 
 
      console.log('This is heading 1') 
 
     } else { 
 
      if ($(ele).is('h2')) { 
 
       console.log('This is heading 2') 
 
      } 
 
     } 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<h1>This is heading 1</h1> 
 
<h2>This is heading 2</h2> 
 
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
 
    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
 
    when an unknown printer took a galley of type and scrambled it to make a type 
 
    specimen book. It has survived not only five centuries, but also the leap into 
 
    electronic typesetting, remaining essentially unchanged. It was popularised 
 
    in the 1960s with the release of Letraset sheets containing Lorem Ipsum 
 
    passages, and more recently with desktop publishing software like Aldus 
 
    PageMaker including versions of Lorem Ipsum.</p>

2

我不沒想到你能得到選擇器。但是,由於您是通過標籤名稱選擇的,因此您可以獲得該標籤。

$("p, h1, h2").each(function() { 
    console.log("CSS Selector: ", this.tagName) 
}); 

如果你被選擇的類,你可以測試:

$(".class1, .class2").each(function() { 
    if ($(this).hasClass("class1")) { 
     console.log("class1"); 
    } else { 
     console.log("class2"); 
    } 
}); 
0

如果你的選擇是唯一的標記名稱或只有類可以按照@gaetanoM或@Brmar的答案,但如果您將使用更復雜的選擇,你可以使用下面

var selector = "p.first, h1, h2, p#amazing"; 
var selectors = selector.split(', '); 
var jqObject = $(selector); 

jqObject.each(function(index, el) { 
    selectors.forEach(function(sel, i) { 
     if (el.matches(sel)) { 
      console.log(el, 'matching', sel); 
     }; 
    }); 
}); 

唯一代碼在這裏注意的是,在你選擇的字符串所有的選擇必須由逗號空間012分開。正如你從代碼中看到的那樣,你得到了jquery對象裏面有元素並迭代它們,在每次迭代中你檢查元素是否匹配選擇器數組中的任何選擇器,如果它匹配註銷元素, matching和選擇器。 .matches()在這種情況下非常方便。

Codepen