清除文字但保留图像<a> hyperlinks using jQuery</a>

时间:2013-05-04 17:21:43

标签: jquery

如何删除“产品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>

我尝试过:

$j('span.product-field-display a').html('');

和:

$j('span.product-field-display a').text('');

但它全部被清除,而不仅仅是文本

4 个答案:

答案 0 :(得分:4)

您可以抓取图像,清除锚点,然后放回图像:

$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;
    }
});

答案 1 :(得分:1)

你可以试试这个

$('.product-field-display a').filter(function(){
    return $(this).html($(this).find('img'));
});

DEMO.

答案 2 :(得分:1)

由于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]);
    }
  }
});

答案 3 :(得分:1)

尝试这对我有用

&#13;
&#13;
$('#AddToWishList').click(function(e) {
  e.preventDefault();
  var dt ='Product_ID=1';
  var $this = $(this);
  var img = new Image();
  img.src="images/progress.gif";
  $this.empty().append(img);
  $.post('ajax/add_wish.php', dt, function(data) {	
    $this.empty().append('<i class="fa fa-star"></i>Wishlist');
    $this.attr('class','btn btn-block btn-primary');
    $this.attr('disabled','disabled');				
  });
});
&#13;
<a class="btn btn-block btn-default" href="JavaScript:;;" id="AddToWishList"><i class="fa fa-star"></i>Wishlist</a>
&#13;
&#13;
&#13;