我想在外部标签上附加/预先添加一个空格。
我尝试了以下方法:
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[ test1, test2, test3]',
'html': $('<span>', {
'text': 'test4',
'css': {
backgroundColor: 'yellow'
}
})
});
$elem.append(" ")
$elem.prepend(" ");
console.log($elem[0]);
console.log($elem[0].innerHTML);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
如您所见,只有内部标签有空格。
但是,我想将它放在外标签上。像下面这样:
<span data-function="addSynonym" data-options="[ test1, test2, test3]"><span style="background-color: yellow;">test4</span></span>
Run Code Online (Sandbox Code Playgroud)
任何建议如何做到这一点?
我感谢您的回复!
您可以使用另一个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);
}Run Code Online (Sandbox Code Playgroud)
#editor {
border: 1px solid grey;
height: 100px;
margin-bottom: 10px;
overflow-wrap: break-word;
overflow: auto;
}
#elem_html {
white-space: normal;
margin-top: 20px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editor"></div>
<div>
<button id="add_text">Add text</button>
<button id="change_text_color">Change color</button>
</div>
<div>
<pre id="elem_html"></pre>
</div>Run Code Online (Sandbox Code Playgroud)
如您所见,您可以$elem使用span选择器 ( $elem.find('span')) 或更具体地使用data-function名称span[data-function="addSynonym"]( $elem.find('span[data-function="addSynonym"]')) 以及内部元素span > span或span[data-function="addSynonym"] > span.
如果您想保留该特定$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);
}Run Code Online (Sandbox Code Playgroud)
#editor {
border: 1px solid grey;
height: 100px;
margin-bottom: 10px;
overflow-wrap: break-word;
overflow: auto;
}
#elem_html {
white-space: normal;
margin-top: 20px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editor"></div>
<div>
<button id="add_text">Add text</button>
<button id="change_text_color">Change color</button>
</div>
<div><pre id="elem_html"></pre></div>Run Code Online (Sandbox Code Playgroud)
使用这种方式,您必须仅使用span( $elem.find('span')) 选择器访问内部跨度。