我如何删除“Product X”并仅使用 jquery 保留图像?
<span class="product-field-display">
<a href="/products/product-a-detail" original-title="Product A">
<img alt="product-a" src="/images/resized/product_a_180x180.png">Product A</a>
</span>
<span class="product-field-display">
<a href="/products/product-b-detail" original-title="Product B">
<img alt="product-b" src="/images/resized/product_b_180x180.png">Product B</a>
</span>
Run Code Online (Sandbox Code Playgroud)
我尝试过:
$j('span.product-field-display a').html('');
Run Code Online (Sandbox Code Playgroud)
与:
$j('span.product-field-display a').text('');
Run Code Online (Sandbox Code Playgroud)
但它全部被清除了,不仅仅是文本
您可以抓取图像,清除锚点,然后将图像放回去:
$j('#gkComponent .productdetails-view .product-related-products .product-field-type-R span.product-field-display a').each(function() {
var $this = $(this);
var img = $this.find('img').detach();
$this.empty().append(img);
});
Run Code Online (Sandbox Code Playgroud)
或者通过 DOM 从锚点中删除所有文本节点,保持元素img完好无损:
$j('#gkComponent .productdetails-view .product-related-products .product-field-type-R span.product-field-display a').each(function() {
var node, nextNode;
node = this.firstChild;
while (node) {
nextNode = node.nextSibling;
if (node.nodeType === 3) { // 3 = text node
node.parentNode.removeChild(node);
}
node = nextNode;
}
});
Run Code Online (Sandbox Code Playgroud)