[英]Wrap only selected text with a html tag using javascript
I am trying to wrap only selected text with a specific tag using javascript tag. 我试图使用javascript标签仅包装具有特定标签的选定文本。 I find a code but when I click a button then it will add a tag which I don't want because I only want to apply the tag around selected element.
我找到了一个代码但是当我点击一个按钮然后它会添加一个我不想要的标签,因为我只想在所选元素周围应用标签。
Example JS code: JS代码示例:
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$('#bold').click(function() {
wrapText("myTa", "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("myTa", "<em>", "</em>");
});
$('#underline').click(function() {
wrapText("myTa", "<u>", "</u>");
});
$('#code').click(function() {
wrapText("myTa", "<pre><code>", "</code></pre>");
});
This is the Full working code Link 这是完整的工作代码链接
Any help will be appreciated. 任何帮助将不胜感激。
Use this condition: if(start != end){ ... }
使用此条件:
if(start != end){ ... }
http://jsfiddle.net/sherali/bd4np/119/ http://jsfiddle.net/sherali/bd4np/119/
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
if (start != end){
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.