javascript - 单击单词以选择并作为答案提交
问题描述
我需要在单击时选择一个单词,并在单击提交按钮后提交数据表的答案列。
这是我的选择字代码。另外,单击所选单词后,我需要取消选择单词。
<!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>
解决方案
从评论中我发现您的问题是您无法取消选择单词。我已经修改了您的代码,因此可以取消选择。只添加了一个 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/
推荐阅读
- c# - C# Wpf 在运行时嵌入图像
- xml - 使用 groovy 脚本使用 XmlSlurper 提取元素值
- react-native - react-native Avatar 元素为 uri 属性添加授权标头
- vue.js - 使用类绑定时未显示 Vue 错误页面
- python - QTreeView 拖放:QAbstractItemView.InternalMove 允许拖放外部视图?
- ios - 用户选择后应用跟踪透明度重置
- python - 序数编码:如何对满足特定条件的值进行编码?
- java - Mkdir() 在 Android Realme 设备中不起作用?
- c++ - C ++设置允许重复?
- python - 如何在 spyder anaconda 中安装 arcpy