問題出處:http://stackoverflow.com/questions/8803470/basic-html-also-allowed
原發問者想利用個按鈕來把某個區塊中的超鏈結文字內容轉換成實際的超鏈結或是取消超連結,像是
檢視原始碼 HTML
1 2 3 4 5 6 7 8 | <body> <div id="links"> http://google.com <br> http://facebook.com <br> http://youtube.com </div> <button>Toggle!</button> </body> |
變成
檢視原始碼 HTML
1 2 3 4 5 6 7 8 | <body> <div id="links"> <a href="http://google.com">http://google.com</a> <br /> <a href="http://facebook.com">http://facebook.com</a> <br /> <a href="http://youtube.com">http://youtube.com</a> </div> <button>Toggle!</button> </body> |
這樣的效果其實可以用在像是留言版中會過濾 html tag 的部份,可以在當瀏覽時在依情況來轉換成真的超鏈結。網友 techfoobar 提供了簡單的方法並包裝成外掛:
檢視原始碼 JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $.fn.replaceUrl = function() { // 如果有找到超鏈結, 表示已經轉換過 if($(this).find('a').length > 0) { // 把超鏈結轉成一般文字 $(this).find('a').each(function() { $(this).replaceWith($(this).text()); }); } else { // 如果沒有找到超鏈結時, 利用正規表示法來找出符合超鏈結的格式 var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi; // 把超鏈結文字轉成超鏈結 this.each(function() { $(this).html( $(this).html().replace(regexp, '<a href="$1">$1</a>')); }); } return $(this); } $().ready(function() { $('button').click(function() { $('div').replaceUrl(); }); }); |