代码之家  ›  专栏  ›  技术社区  ›  Internet man

使用jquery为具有特定类的元素创建链接

  •  0
  • Internet man  · 技术社区  · 17 年前

    如何用DIV中的文本构建的链接包装属于特定类的每个元素?我的意思是我想转身:

    <foo class="my-class>sometext</foo>
    

    进入之内

    <a href="path/sometext" ><foo class="my-class>sometext</foo></a>
    

    URL编码字符也不错,但如果需要,现在可以忽略。

    编辑 :为了澄清,路径取决于元素中的文本。

    5 回复  |  直到 17 年前
        1
  •  2
  •   cletus    17 年前

    使用 jQuery.wrap() 对于简单情况:

    $(".my-class").wrap("<a href='path/sometext'></a>");
    

    要在内部处理文本:

    $(".my-class").each(function() {
      var txt = $(this).text();
      var link = $("<a></a>").attr("href", "path/" + txt);
      $(this).wrap(link[0]);
    });
    
        2
  •  2
  •   Sampson    17 年前
    $(".my-class").each(function(){
      var thisText = $(this).text();
      $(this).wrap("<a></a>").attr("href","path/"+thisText);
    });
    
        3
  •  1
  •   TheVillageIdiot    17 年前

    您可以像这样将它们包装在锚定元素中:

    $(document).ready(function(){
        $(".my-class").each(function(){
               var hr="path/"+$(this).text();
               $(this).wrap("<a href='"+hr+"'></a>");
       });
    });
    

    如果要在同一页中打开链接,则比修改DOM将元素包装在定位点中更容易的方法是为元素定义CSS,使它们看起来像链接,然后处理click事件:

    $(".my-class").click(function(){
         window.location.href="path/"+$(this).text();
    });
    
        4
  •  0
  •   Russ Cam    17 年前
    $("foo.my-class").each(function(){
      var foo = $(this);
      foo.wrap("<a href='path/" + foo.Text() +"'>");
    });
    
        5
  •  0
  •   John Fisher    17 年前

    应该这样做:

    $('foo.my-class').each(function() {
      var element = $(this);
      var text = element.html(); // or .text() or .val()
      element.wrap('<a href="path/' + text + '"></a>');
    });