代码之家  ›  专栏  ›  技术社区  ›  kitsune

在jquery的html(val)语句中访问当前选定元素的内容?

  •  1
  • kitsune  · 技术社区  · 15 年前

    我有几个 链接 我想用基于文本内容的自动生成的图像替换其文本内容。

    所以现在看起来是这样的:

    <a href="blabla" class="mLink">
    <span class="mText">The Text in Question</span>
    </a>
    

    我想要两个

    <a href="blabla" class="mLink">
    <img src="/ImageTextHandler.ashx?message=The+Text+in+Question" alt="The Text in Question"/>
    </a>
    

    <a href="blabla" class="mLink">
    <span class="mText">
        <img src="/ImageTextHandler.ashx?message=The+Text+in+Question" alt="The Text in Question"/>
    </span>
    </a>
    

    如何访问.replaceWith或.html中有问题的元素,以便获取文本内容?

    4 回复  |  直到 15 年前
        1
  •  2
  •   Josh    15 年前

    试试这个

    $(".mLink").each(function (i) {
    
       var thisText = $(this).find(".mText").text();
       $(this).html("<img src='/ImageTextHandler.ashx?
             message=" + thisText + "' alt='" + thisText + "'/>");
    
    });
    
        2
  •  1
  •   Russ Cam    15 年前
    $(function() {    
        var mySpan = $('a.mLink span.mText');
        var text = mySpan.text();
        var link = text.split(' ').join('+');
    
        mySpan.replaceWith($("<img src='/ImageTextHandler.ashx?message=" + link + "' alt='" + text + "'/>"));
    });
    

    Working Demo here

    来自演示的代码

    $(function() {
    
        $('#button').click(function() {
    
          $('a.mLink span.mText').each(function() {    
            var text = $(this).text();
            var link = text.split(' ').join('+');
            $(this).replaceWith($("<img src='/ImageTextHandler.ashx?message=" + link + "' alt='" + text + "'/>"));
          });
    
        });
    });
    
        3
  •  1
  •   peirix    15 年前

    使用本地化选择器

    $(".mLink").each(function() {
        var text = $("span", this).text();
        $("span", this).replaceWith("<img src='/ImageTextHandler.ashx?message="+
                                      text+"' alt='"+text+"' />");
    });
    
        4
  •  0
  •   belugabob    15 年前

    试试这样的…

    $(".mText").each(function(){
      var url = "/ImageTextHandler.ashx?message=" + escape($(this).text());
      var image = $("<img>");
      image.attr("src") = url;
      image.attr("alt") = $(this).text();
      $(this).text("");
      $(this).append(image);
    });