将div中的所有链接替换为帖子

时间:2013-07-26 19:59:27

标签: javascript jquery html

我在页面上有几个链接,我有兴趣替换特定div中的所有链接,指向一个main.php,链接作为帖子发布到链接...

使用example.php:

 <div id='mainpg'>
    <a href='test123.html'>TEST1</a>
    <a href='test123.html'><img src=1213.jpg/></a>
 </div>
 <a href='back'>back</a>

我想使用javascript或jquery来获取以下内容

Example.php(带脚本):

 <div id='mainpg'>
    <a href='main.php?href=test123.html'>TEST1</a>
    <a href='main.php?href=test123.html'><img src=1213.jpg/></a>
 </div>
 <a href='back'>back</a>

也不确定是否需要担心urlencode,因为之前已经是链接。

谢谢, JT

5 个答案:

答案 0 :(得分:1)

links = document.getElementById("name of div").getElementsByTagName("a")

for(i=0;i<links.length;i++)
    links.href="main.php?"+links.href

答案 1 :(得分:1)

$('#mainpg a').each(function(i) {
    $(this).attr('href', 'main.php?href=' + $(this).attr('href'));
});

答案 2 :(得分:1)

$('#mainpg a').each(function() {
    var newRef = 'main.php?href=' + $(this).attr('href');
    $(this).attr('href', newRef);
});

答案 3 :(得分:1)

jQuery.each($('#mainpg a'), function() {
  $(this).attr('href','main.php?href='+$(this).attr('href'));
});

http://jsfiddle.net/wQ83t/1/

答案 4 :(得分:0)

使用jQuery,您可以使用$ .each迭代链接并更改href属性。

这样的事情:

jQuery(document).ready(function($){
  $('a').each(function(index, value){
    $(this).attr('href', 'main.php?'+($this).attr('href'));
 }

 });

你可能需要稍微调整一下,不测试它。

相关问题