Отображение выбранных слов [Javascript] - PullRequest
0 голосов
/ 11 мая 2019

Слова внутри предложения подсвечиваются при щелчке мышью. Это работает прямо здесь.

Но; Показывать выделенные слова кнопкой, к сожалению, не работает.

JSFiddle

words = [];
var sentence = $('.sentence').html().split(/\s+/),
  result = [];


for (var i = 0; i < sentence.length; i++) {
  result[i] = '<span>' + sentence[i] + '</span>';
  var a = sentence[i];
}

$('.sentence').html(result.join(' '));

if (a.indexOf(" ") + 1) {
  alert('fail: ' + a);
} else {
  words.push(a);
}

$('.sentence').on('click', 'span', function() {
  $(this).addClass('highlight');
});

$('button').click(function() {
  alert(words);
});

$('$selectedWords').innerHTML = words;
.sentence span:hover,
.highlight {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="sentence">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique aliquam totam odit excepturi reiciendis quam doloremque ab eius quos maxime est deleniti praesentium. Quia porro commodi blanditiis iure dicta voluptatibus.</p>



Selected words:
<p id="selectedWords"></p>

<button>Show in alert</button>

Ответы [ 2 ]

0 голосов
/ 11 мая 2019

Из вашего кода вы никогда не отслеживали созданные вами элементы span, и в результате не было никакого способа узнать, какой именно элемент был выделен. Я изменил код к этому:

words = [];
var sentence = $('.sentence').html().split(/\s+/),
  result = [];


for (var i = 0; i < sentence.length; i++) {
  //notice that I used the index to bind the id of the span element so that we can retrieve it binded index as the id later
  result[i] = '<span id="'+i+'">' + sentence[i] + '</span>';
}
$('.sentence').html(result.join(' '));
$('.sentence').on('click', 'span', function() {
  $(this).addClass('highlight');
  let id = $(this).prop('id'); // retrieve the binded index as the id
  let a = $(result[id]).text(); //get the selected span element from the result array with the retrieved id and extract the inner text from the span element
  if (a.indexOf(" ")+ 1) {
  alert('fail: ' + a);
} else {
  words.push(a); //push the extracted inner text to the words array
} 
});

$('button').click(function() {
  alert(words);
});

//$('$selectedWords').innerHTML = words;
.sentence span:hover,
.highlight {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="sentence">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique aliquam totam odit excepturi reiciendis quam doloremque ab eius quos maxime est deleniti praesentium. Quia porro commodi blanditiis iure dicta voluptatibus.</p>



Selected words:
<p id="selectedWords"></p>

<button>Show in alert</button>

Надеюсь, это отлично работает.

0 голосов
/ 11 мая 2019

Взгляните на JSFiddle, который я собрал для начала. Это не самое лучшее, но, надеюсь, направит вас в правильном направлении.

https://jsfiddle.net/qt9hgbkp/

JavaScript, который приводит пример в действие ...

/**
 * Sentence element
 * @var {Object}
 */
var $sentence = $('.sentence');

/**
 * Selected words output element
 * @var {Object}
 */
var $selected = $('#selectedWords');

/**
 * Wrap each word in a sentence in a span
 * @param {String} sentence
 * @return {String}
 */
function wrapSentence(sentence) {
    // Get element contents and split by whitespace
  var words = $sentence.text().split(/\s+/);
  // Create an empty array for storing wrapped elements
  var wrapped = [];

  // Loop through each word and wrap
  for (var i = 0; i < words.length; i++) {
    wrapped.push('<span>' + words[i] + '</span>');
  }

    // 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;
}

/**
 * Override original html with wrapped
 */
$sentence.html(wrapSentence());

/**
 * Handle click event for each span in sentence
 */
$sentence.on('click', 'span', function() {
    // Add/remove the highlight class
    $(this).toggleClass('highlight');
  // Update the selected output
  $selected.text( getSelected().join( ', ' ) );
});

/**
 * Alert the user with selected words
 */
$('button').on( 'click', function() {
    alert( getSelected() );
} );
...