Метод 1: Оберните ваш узел другим узлом без пробела в начале / конце
Вы можете использовать другой элемент span
для переноса текста. Это не повлияет ни на что в вашем тексте, так же как вы не захотите использовать $elem
впоследствии. Затем создайте текстовый узел, используя NO-BREAK SPACE' (U+00A0)
, что эквивалентно
, и используйте его для компиляции вашего окончательного текстового узла.
var colors = ['yellow', 'red', 'lightgreen', 'cyan'];
var currentColor = 0;
// Create a text node using Unicode Character 'NO-BREAK SPACE' (U+00A0)
var $spaceNode = $(document.createTextNode('\u00A0'));
// Wrap the text node to a span with a begin and end sibling of the space text node clone
var $elem = $('<span>').append(
$spaceNode.clone(),
$('<span>', {
'data-function': "addSynonym",
'data-options': '[test1, test2, test3]',
'html': $('<span>', {
'text': 'test4',
'css': {
backgroundColor: 'yellow'
}
})
}),
$spaceNode.clone()
);
function appendText() {
// Output $elem node outer HTML to a preview element
$('#elem_html').text($elem[0].outerHTML);
// Clone the $elem so we can use it multiple times
var $elemClone = $elem.clone();
// Append the cloned $elem to the DOM
$('#editor').append($elemClone);
// Apply manipulation demo timer
hookElemChange($elemClone);
}
// Handle add text button click
$('#add_text').on('click', function() {
appendText();
});
// Handle change $elem color button click
$('#change_text_color').on('click', function() {
var newColor;
// Generate a random color
do {
newColor = Math.floor(Math.random() * Math.floor(colors.length));
} while(newColor === currentColor);
currentColor = newColor;
// Change the $elem inner span background color to a random color
$elem.find('span > span').css('background-color', colors[currentColor]);
// We can also use specific element selector using data-function with "addSynonym" value
// $elem.find('span[data-function="addSynonym"] > span').css('background-color', colors[currentColor]);
// Append the text to the DOM
appendText();
});
// A timer for each element that parses and increases the text prepending number
// This is for to demontrate that each node can be manipulated with no restrictions after creating/cloning
function hookElemChange($element) {
setInterval(function() {
var $currentElem = $element.find('span[data-function="addSynonym"] > span');
var text = $currentElem.text();
var textParts = text.match(/([a-z]+)(\d+)/);
if (textParts) {
var num = parseInt(textParts[2]);
var newText = textParts[1] + ++num;
$currentElem.text(newText);
}
}, 1000);
}
#editor {
border: 1px solid grey;
height: 100px;
margin-bottom: 10px;
overflow-wrap: break-word;
overflow: auto;
}
#elem_html {
white-space: normal;
margin-top: 20px;
}
Как вы можете видеть, вы можете сохранить и получить доступ к каждому клонированному $elem
впоследствии с помощью обоих span
селектор ($elem.find('span')
) или даже более конкретный c с использованием data-function
имя span[data-function="addSynonym"]
($elem.find('span[data-function="addSynonym"]')
) и для внутреннего элемента span > span
или span[data-function="addSynonym"] > span
.
Метод 2: Добавить все непосредственно к целевому узлу (пробел / $ elem / space)
Другой способ - напрямую добавить все к целевому узлу, если вы хотите сохранить указанную c $elem
структуру:
var colors = ['yellow', 'red', 'lightgreen', 'cyan'];
var currentColor = 0;
// Create a text node using Unicode Character 'NO-BREAK SPACE' (U+00A0)
var $spaceNode = $(document.createTextNode('\u00A0'));
// Create the node with initial structure
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[test1, test2, test3]',
'html': $('<span>', {
'text': 'test4',
'css': {
backgroundColor: 'yellow'
}
})
});
function appendText() {
// Clone the $elem so we can use it multiple times
var $elemClone = $elem.clone();
// Append the cloned $elem to the DOM
$('#editor').append($spaceNode.clone(), $elemClone, $spaceNode.clone());
// Output #editor node inner HTML to a preview element
$('#elem_html').text($('#editor')[0].innerHTML);
// Apply manipulation demo timer
hookElemChange($elemClone);
}
// Handle add text button click
$('#add_text').on('click', function() {
appendText();
});
// Handle change $elem color button click
$('#change_text_color').on('click', function() {
var newColor;
// Generate a random color
do {
newColor = Math.floor(Math.random() * Math.floor(colors.length));
} while(newColor === currentColor);
currentColor = newColor;
// Change the $elem inner span background color to a random color
$elem.find('span').css('background-color', colors[currentColor]);
// We can also use specific element selector using data-function with "addSynonym" value
// $elem.find('span[data-function="addSynonym"] > span').css('background-color', colors[currentColor]);
// Append the text to the DOM
appendText();
});
// A timer for each element that parses and increases the text prepending number
// This is for to demontrate that each node can be manipulated with no restrictions after creating/cloning
function hookElemChange($element) {
setInterval(function() {
var $currentElem = $element.find('span');
var text = $currentElem.text();
var textParts = text.match(/([a-z]+)(\d+)/);
if (textParts) {
var num = parseInt(textParts[2]);
var newText = textParts[1] + ++num;
$currentElem.text(newText);
}
}, 1000);
}
#editor {
border: 1px solid grey;
height: 100px;
margin-bottom: 10px;
overflow-wrap: break-word;
overflow: auto;
}
#elem_html {
white-space: normal;
margin-top: 20px;
}
Используя этот способ, вам нужно будет получить доступ к внутреннему интервалу, используя span
($elem.find('span')
) селектор.