2016-12-28 27 views
0

在我的textarea當我選擇文本時,我可以點擊我的超鏈接模式,並打開它。jQuery添加數字超鏈接以確定鏈接

我可以設置標題和網址。

出來放像["example"]("http://www.example.com")

Codepen DEMO

問題我怎樣才能得到它,所以當我每次添加鏈接也可以擁有對姓名和號碼並點擊以下鏈接如下所述。

我盡力去實現它,其中參考式鏈接,您可以參考你的鏈接通過名字,您在文檔中的其他地方定義:

I get 10 times more traffic from [Google][1] than from 
[Yahoo][2] or [MSN][3]. 

[1]: http://google.com/  "Google" 
[2]: http://search.yahoo.com/ "Yahoo Search" 
[3]: http://search.msn.com/ "MSN Search 

我的腳本

$('#link').on('click', function (event) { 
    var textArea = $('#message'), 
     len = textArea.val().length, 
     start = textArea[0].selectionStart, 
     end = textArea[0].selectionEnd, 
     selectedText = textArea.val().substring(start, end); 

    $('input#title').val(selectedText); 

    $('input#url').val('http://'); 

    $('#save-link').on("click",function(e) { 
     e.preventDefault(); 

     $('#myLink').modal('hide'); 

     replacement = '["'+ $('input#title').val() +'"]("'+ $('input#url').val() +'")'; 


     wrapLink(replacement); 
    }); 
});  

function wrapLink(link) { 
    var textArea = $('#message'), 
     len = textArea.val().length, 
     start = textArea[0].selectionStart, 
     end = textArea[0].selectionEnd, 
     selectedText = textArea.val().substring(start, end); 
    textArea.val(textArea.val().substring(0, start) + link + textArea.val().substring(end, len)); 
    $('#message').keyup(); 
} 

回答

0

解決方案到目前爲止,我已經解決了新的問題EXAMPLE HERE

舊的代碼有幾個錯誤。

$('#myLink').on('shown.bs.modal', function() { 
    var text = getSelectedText(); 
    $('#title').val(text); 
    $('#url').val('http://'); 
});  

function getSelectedText() { 
    var textarea = document.getElementById("message"); 
    var len = textarea.value.length; 
    var start = textarea.selectionStart; 
    var end = textarea.selectionEnd; 
    var sel = textarea.value.substring(start, end); 
    return sel; 
} 

var counter = 0; 

$('#save-link').on('click', function(e) { 
    var textarea = document.getElementById("message"); 
    var len = textarea.value.length; 
    var start = textarea.selectionStart; 
    var end = textarea.selectionEnd; 
    var sel = textarea.value.substring(start, end); 

    var replace = '[' + $('input#title').val() + ']' + '[' + counter + ']'; 

    var id = '[' + counter + ']: ' + $('input#url').val(); 

    counter++; 

    if ($.trim(sel) == '') { 
     return false; 
    } else { 
     textarea.value = textarea.value.substring(0,start) + replace + 
     textarea.value.substring(end,len) + '\n' + id; 

    } 
}); 
+0

http://codepen.io/anon/pen/BQXQzY – Viney