例如,如果文本中具有字体大小或其他标签,它将完全删除它。
代码前;
<p id="TextHere">[...] <span style='color:red'>people</span> and 10<sup>12</sup>, [...]</p>
代码后;
<p id="TextHere">[...] <span>people</span>, <span>and</span> <span>1012</span>[...]</p>
如果有样式或类的标签被删除。
如果单词中有标签;如何保护该标签?
在示例代码的全文中; <sup>
和<span style>
标签可用,但是这些标签在Javascript代码工作后不会显示。
完整代码:
/**
* Sentence element
* @var {Object}
*/
var $sentence = $('#TextHere');
/**
* Selected words output element
* @var {Object}
*/
var $selected = $('#selectedWords');
var previosSelectedWords = 'aute,dolor';
var PSW = previosSelectedWords.split(',');
/**
* Wrap each word in a sentence in a span
* @param {String} sentence
* @return {String}
*/
function wrapSentence(sentence) {
// Get element contents and split by whitespacegit
var words = $sentence.text().split(/\s+/);
// Create an empty array for storing wrapped elements
var wrapped = [];
// Loop through each word and wrap
for (var j = 0; j < PSW.length; j++) {
for (var i = 0; i < words.length; i++) {
if (PSW[j] == words[i]) {
var prevS = '<span class="previosSelecteds">' + words[i] + '</span>';
words[i] = prevS;
}
}
}
for (var i = 0; i < words.length; i++) {
if (!words[i].includes('previosSelecteds')) {
wrapped.push('<span>' + words[i] + '</span>');
}
else {
wrapped.push(words[i]);
}
}
// Combine words into a string
return wrapped.join(' ');
}
/**
* Find all selected words in $sentence element
* @return {Array}
*/
function getSelected() {
// Create an empty array for storing selected words
var selected = [];
// Find all spans with the highlight class
$sentence.find('span.highlight').each(function() {
// Push span values to array
selected.push($(this).text());
});
// Return results
return selected;
}
$sentence.html(wrapSentence());
$sentence.on('click', 'span', function() {
// Add/remove the highlight class
$(this).toggleClass('highlight');
// Update the selected output
$selected.text(getSelected().join(', '));
document.getElementById("ImWo").value = getSelected();
});
如何保护现有标签?