我已经能够查询SelectorAll 正确的className、标签和href。我试图拆分我的结果,所以我只有 SKU #。
HTML
<div class="mini-cart-product-name">
<a href="http://example.com/product/12345.html">Product 1</a>
</div>
<div class="mini-cart-product-name">
<a href="http://example.com/product/67890.html">Product 2</a>
</div>
JS
function GetCartProducts() {
var URL = document.querySelectorAll(".mini-cart-product-name a[href*='/product/']");
for (var i = 0; i < URL.length; i++) {
console.log(URL.item(i));
<a href="http://example.com/product/12345.html">Product 1</a>
</div>
<a href="http://example.com/product/67890.html">Product 2</a>
</div>
// Split result/href to only have the SKU # //
// Push to array
// Desired result
// var array ["12345","67890"]
}
}
该函数可以是这样的一行。
function GetCartProducts() {
return Array.from(document.querySelectorAll(".mini-cart-product-name a[href*='/product/']"))
.map(el => el.href.replace(/^.+product\/(.+?)\.html.*?/i, '$1'))
}
console.log(GetCartProducts());
<div class="mini-cart-product-name">
<a href="http://example.com/product/12345.html">Product 1</a>
</div>
<div class="mini-cart-product-name">
<a href="http://example.com/product/67890.html">Product 2</a>
</div>
的一些解释/^.+product\/(.+?)\.html/i
。
/whatever/
是正则表达式
^
开始输入的
.
任何字符+
重复一次或更多次
\.
点本身
(.+?)
捕获模式。+?
一个或多个非贪婪的
$1
捕获文本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句