首页 > 解决方案 > 单击单词以选择并作为答案提交

问题描述

我需要在单击时选择一个单词,并在单击提交按钮后提交数据表的答案列。

这是我的选择字代码。另外,单击所选单词后,我需要取消选择单词。

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Click a word in the paragraph and highlight it.</title>
</head>
<body>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.
</p>
<textarea name="ans" rows="4" cols="50"></textarea>
</body>
<script>
var words = $( "p" ).first().text().split( /\s+/ );
var text = words.join( "</span> <span>" );
$( "p" ).first().html( "<span>" + text + "</span>" );
$( "span" ).on( "click", function() {
$( this ).css( "background-color", "red" );
});
</script>
</html>

标签: javascripthtmljquery

解决方案


从评论中我发现您的问题是您无法取消选择单词。我已经修改了您的代码,因此可以取消选择。只添加了一个 IF 来做到这一点:

    $(document).ready(function() {
      var words = $( "p" ).first().text().split( /\s+/ );
      var selectedWords = [];
      var text = words.join( "</span> <span>" );
      $( "p" ).first().html( "<span>" + text + "</span>" );
      $( "span" ).on( "click", function() {
        var word = $(this).html();
        if($(this).css("background-color") == 'rgb(255, 0, 0)') {
            $( this ).css( "background-color", "transparent" );
          var index = selectedWords.indexOf(word);
                if (index !== -1) selectedWords.splice(index, 1);
        } else {
            $( this ).css( "background-color", "rgb(255, 0, 0)" );
          selectedWords.push(word);
        }
        $('textarea').html(selectedWords.join(','));
      });
    });

这里也是工作代码:https ://jsfiddle.net/42yem8kv/6/


推荐阅读