2009-08-24 146 views
0

如何使用从div内的文本构建的链接来包装属于特定类的每个元素?我的意思是,我想谈谈:使用jQuery为特定类的元素创建链接

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

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

URL编码字符也将是不错的,但可现在如果有必要忽略。

编辑:只是为了澄清,路径依赖于文本的元素

回答

2

使用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
$(".my-class").each(function(){ 
    var thisText = $(this).text(); 
    $(this).wrap("<a></a>").attr("href","path/"+thisText); 
}); 
1

你可以把它们包裹起来德锚元素是这样的:

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

如果您打开在同一页面本身则容易单向链接不是修改DOM包装元素中的锚是定义CSS的元素,使它们看起来像链接,然后处理单击事件:

$(".my-class").click(function(){ 
    window.location.href="path/"+$(this).text(); 
}); 
+0

小心使用$(本)。html的()。最好使用$(this).text()来避免包含任何格式标签。 – Sampson 2009-08-24 14:42:41

+0

是的你是对的@Jonathan **。html()**获取所有东西:) – TheVillageIdiot 2009-08-24 15:37:24

0

这应该做到这一点:

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

我想你的意思是$(元素)而不是$元素。 – Sampson 2009-08-24 14:42:10

0
$("foo.my-class").each(function(){ 
    var foo = $(this); 
    foo.wrap("<a href='path/" + foo.Text() +"'>"); 
});