2010-08-25 67 views

回答

1

試試看:http://jsfiddle.net/uJRb6/

var nums = $('p').text().split(/\s*,\s*/); 
var tags = ''; 

    $.each(nums,function(i,val) { 
     tags += '<a href=http://www.example.com/?id=' + val + '>' + val + '</a><br>' 
    }); 
$('body').append(tags);​ 

如果你關注的內容的安全性,你可以這樣做:

var nums = $('p').text().split(/\s*,\s*/); 
var tags = []; 

    $.each(nums,function(i,val) { 
     tags.push($('<a>',{text:val + ' ', href:'http://www.example.com/?id=' + val})); 
    }); 
$(tags).appendTo('body'); 
1

你不需要jQuery的這,你可以使用純javascript來做這件事:

vals = $('p').html().split(','); 
for(var i in vals) { 
    tags += '<a href=http://www.example.com/?id=' + val + '>link</a><br>' 
} 
$('body').append(tags) 
+1

不難,但除了字符串追加,這*是*主要是jQuery :) – 2010-08-25 15:31:05

+0

'for/in'通過Array不是一個好主意。你應該使用'for'循環。 – user113716 2010-08-25 15:34:16

2

You ca n使用正則表達式.replace(),這樣的事情:

​$("p").html(function(i, h) { 
    return h.replace(/\d+/g, function(m) { return "http://www.example.com/?id=" + m; }); 
});​​ 

You can test it out here,或使它們可點擊的鏈接:

$("p").html(function(i, h) { 
    return h.replace(/\d+/g, function(m) { 
    return "<a href='http://www.example.com/?id="+m+"'>"+m+"</a>"; 
    }); 
});​ 

You can give it a try here