想要将标签拆分为两个。我有这样的标签
<span class="ss" custom-attr="kk"> split content here, and have to split </span>
如果我选择内容and have
并单击按钮,我想要像这样拆分标签。偶数span包含许多属性。我想用这些属性分开。
<span class="ss" custom-attr="kk"> split content here, </span>and have <span class="ss" custom-attr="kk">to split </span>
我可以使用window.getSelection()
获取所选文字。
例如:https://jsfiddle.net/rx5ojfwc/
答案 0 :(得分:0)
您可以使用此功能:
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
创建标记并替换内容:
var myNewTag = '</span>' + getSelectionText() + '<span>';
该功能来自用户Tim Down:Get the Highlighted/Selected text
答案 1 :(得分:0)
使用jQuery插件,您可以获取选择,然后执行替换。这是动态的,因此您甚至不需要知道它是否为<span>
标签。
(function($) {
$.getSelectedText = function() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
};
$.fn.spanSelectReplace = function() {
var tag = this.prop('tagName').toLowerCase();
var tStart = '<' + tag + '>';
var tEnd = '</' + tag + '>';
var selText = $.getSelectedText();
return this.replaceWith(tStart + this.html().replace(selText, tEnd + selText + tStart) + tEnd);
}
})(jQuery);
$('button').on('click', function() {
$('span').spanSelectReplace(); // Perform the jQuery function.
console.log($('span').parent().html()); // Print the HTML to the console.
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Split content here, and have to split</span>
<br />
<button>Split</button>
&#13;
<span>Split content here, </span>and have<span> to split</span>
突出显示文本区域中文本的"and have "
部分,然后点击 Split 按钮。
将通过将选择内容包含在封闭开放的<span>
标记中来替换文本。
function splitText(button) {
var formEl = document.getElementById('content');
var selection = getSelection(formEl);
formEl.value = formEl.value.replace(selection, '</span>' + selection + '<span>');
}
function getSelection(field) {
var start = field.selectionStart;
var finish = field.selectionEnd;
return field.value.substring(start, finish);
}
&#13;
textarea { width: 100%; }
&#13;
<textarea id="content" rows="5"><span> split content here, and have to split </span></textarea>
<br>
<input type="button" value="Split" onClick="splitText(this)" />
&#13;
答案 2 :(得分:-1)
您可以非常轻松地使用replace()来完成此操作。
var str = "<span> split content here, and have to split </span>";
var res = str.replace("here,", "here, </span>");
res = res.replace("have ", "have <span>");
答案 3 :(得分:-1)
您可以使用split()和join()以及replace()来实现此目的:
将字符串存储到var:
中var str = "<span> split content here, and have to split </span>";
制作字符串:
str.split(",").join(", </span>").replace("and have", "and have <span>")
var str = "<span> split content here, and have to split </span>";
str.split(",").join(", </span>").replace("and have", "and have <span>")
console.log(str);