Добавить / добавить пробел во внешнем теге - PullRequest
4 голосов
/ 16 февраля 2020

Я хотел бы добавить / добавить пробел к внешним тегам.

Я попробовал следующее:

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;

Любые предложения, как это сделать?

Я ценю ваши ответы!

Ответы [ 6 ]

5 голосов
/ 19 февраля 2020

Метод 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('\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')) селектор.

1 голос
/ 25 февраля 2020

Учитывая, что узлы не знают, что вокруг них происходит, это идеальный сценарий для 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;'
0 голосов
/ 25 февраля 2020

Может быть, это может вам помочь.

Если вы можете добавить псевдо ::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 решение, я думаю, что вы должен добавить место в ваш контейнер элемента.

С уважением

Амин

0 голосов
/ 25 февраля 2020

Есть много способов добавить пространство снаружи элемента. но если вы не оберните его внутри другого диапазона, он не будет работать.

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>
0 голосов
/ 19 февраля 2020

Я бы просто сослался на ваниль 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>
0 голосов
/ 16 февраля 2020

In jQuery, insertBefore / before и insertAfter / after - методы, используемые для вставки элементов до или после целевого элемента.

&nbsp; не является элементом, поэтому вы должны создать текстовый узел:

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

См. Пример:

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...