簡體   English   中英

在外部標簽上附加/前置空格

[英]Append/Prepend space on outer tag

我想在外部標簽上附加/預先添加一個空格。

我嘗試了以下方法:

 var $elem = $('<span>', { 'data-function': "addSynonym", 'data-options': '[ test1, test2, test3]', 'html': $('<span>', { 'text': 'test4', 'css': { backgroundColor: 'yellow' } }) }); $elem.append("&nbsp;") $elem.prepend("&nbsp;"); console.log($elem[0]); console.log($elem[0].innerHTML);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

如您所見,只有內部標簽有空格。

但是,我想將它放在外標簽上。 像下面這樣:

&nbsp;<span data-function="addSynonym" data-options="[ test1, test2, test3]"><span style="background-color: yellow;">test4</span></span>&nbsp;

任何建議如何做到這一點?

我感謝您的回復!

方法 1:將您的節點包裝到另一個節點,在開始/結束時沒有中斷空間

您可以使用另一個span元素來包裝文本。 這不會影響您文本中的任何內容,也不會影響您之后可能想要使用$elem 然后使用NO-BREAK SPACE' (U+00A0)創建一個文本節點,相當於&nbsp; 並使用它來編譯您的最終文本節點。

 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('\ ')); // 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(/([az]+)(\\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; }
 <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>

正如你所看到的,你可以保存和訪問的每個克隆$elem既事后span選擇器( $elem.find('span')或者使用更具體的data-functionspan[data-function="addSynonym"] $elem.find('span[data-function="addSynonym"]') ) 和內部元素span > spanspan[data-function="addSynonym"] > span

方法二:將所有內容直接追加到目標節點(space/$elem/space)

如果您想保留特定的$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('\ ')); // 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(/([az]+)(\\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; }
 <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>

使用這種方式,您必須僅使用span ( $elem.find('span') ) 選擇器訪問內部跨度。

鑒於節點不知道它們周圍發生了什么,這是DocumentFragments的完美場景。

let $fragment = $(document.createDocumentFragment());
let $elem = $('<span>', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('<span>', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$fragment.append('\u00A0', $elem, '\u00A0');

$container.append($fragment);
// $container => '&nbsp;<span...><span...>test4</span></span>&nbsp;'

$elem.append('!');
// $container => '&nbsp;<span...><span...>test4</span>!</span>&nbsp;'

我只會手動引用vanilla outerHTML

 var $elem = $('<span>', { 'data-function': "addSynonym", 'data-options': '[ test1, test2, test3]', 'html': $('<span>', { 'text': 'test4', 'css': { backgroundColor: 'yellow' } }) }); $elem.append("&nbsp;"); $elem.prepend("&nbsp;"); console.log("&nbsp;" + $elem[0].outerHTML + "&nbsp;"); console.log($elem[0].innerHTML);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

有很多方法可以在元素外部附加空間。 但除非你把它包裝在另一個跨度內,否則它不會工作。

 var $elem = $('<span>', { 'data-function': "addSynonym", 'data-options': '[ test1, test2, test3]', 'html': $('<span>', { 'text': 'test4', 'css': { backgroundColor: 'yellow' } }) }); $elem.append("&nbsp;") $elem.prepend("&nbsp;"); const textNode = '&nbsp;' $elem.before(textNode) $elem.after(textNode) console.log($elem[0]); console.log($elem[0].innerHTML); var $elemupdated = $('<span>', { 'html': $elem[0].innerHTML }); console.log($elemupdated[0].outerHTML);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

也許這可以幫助你。

如果您可以將偽::after ::before添加到您的樣式中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .mySpan::before{
            content: ' ';
        }
        .mySpan::after{
            content: ' ';
        }
    </style>
</head>
<body>
    <div id="target">my text</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        var $elem = $('<span>', {
            'class': 'mySpan',
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('<span>', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
})


    $("#target").append($elem)


    </script>
</body>
</html>

如果您想要純 Javascript 解決方案,我認為您必須為元素容器添加空間。

親切的問候

阿明

在 jQuery 中, insertBefore / beforeinsertAfter / after是用於在目標元素之前或之后插入元素的方法。

&nbsp; 不是元素,所以你必須創建一個文本節點:

const textNode = '&nbsp;'
$('.some-element').before(textNode)
$('.some-element').after(textNode)

見示例:

https://jsfiddle.net/yq1jfd5z/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM