清除文本,但将图像保留在内部<;a>;使用jQuery的超链接
如何使用jquery删除“产品X”并仅保留图像清除文本,但将图像保留在内部<;a>;使用jQuery的超链接,jquery,Jquery,如何使用jquery删除“产品X”并仅保留图像 <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-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>
以及:
$j('span.product-field-display a').text('');
但是它会被全部清除,而不仅仅是文本您可以抓取图像,清除锚定,然后将图像放回:
$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);
});
或者通过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;
}
});
你可以试试这个
$('.product-field-display a').filter(function(){
return $(this).html($(this).find('img'));
});
由于jQuery不能很好地处理文本节点,一种方法是在纯JS中处理它:
$('span.product-field-display a').each(function() {
var nodes = this.childNodes;
for (var i = nodes.length - 1; i >= 0; --i) {
if (nodes[i].nodeType == 3) {
this.removeChild(nodes[i]);
}
}
});
试试这个对我有用
$('AddToWishList')。单击(函数(e){
e、 预防默认值();
var dt='Product_ID=1';
var$this=$(this);
var img=新图像();
img.src=“images/progress.gif”;
$this.empty().append(img);
$.post('ajax/add_wish.php',dt,函数(数据){
$this.empty().append('Wishlist');
$this.attr('class','btn btn block btn primary');
$this.attr('disabled','disabled');
});
});代码>
@Alex:完全是你的电话,两个都可以。除非你有上万个,否则就不必担心哪一个更有效。第一个较短。:-)谢谢,这很有效!这是我将使用的,因为它看起来更清晰,但我仍然必须接受T.J的答案,它更快!我认为堆栈溢出增加接受答案的延迟太愚蠢了,人们仍然试图给你更多他们不需要的答案:S
$('span.product-field-display a').each(function() {
var nodes = this.childNodes;
for (var i = nodes.length - 1; i >= 0; --i) {
if (nodes[i].nodeType == 3) {
this.removeChild(nodes[i]);
}
}
});