【发布时间】:2020-07-07 17:40:21
【问题描述】:
我正在构建一个可排序的单词测验,用户必须将句子中的单词按正确的顺序排列。这个想法是用户从句子下方拖动单词,然后根据他们的解决方案是否与答案匹配,单词块会亮起绿色或红色。
我正在使用 jQuery 和 jQuery UI 可排序方法。 jQuery sortable 和 HTML & CSS 都可以正常工作,但在我的 JavaScript if 语句中,将答案字符串与用户解决方案字符串进行比较总是 false 无论如何。真正奇怪的是,据我所知,console.log 显示的字符串在各个方面都是相同的。即 typeof 显示它们都是“字符串”类型,两个字符串的长度都显示为 31。我什至添加了一些代码来删除字符串末端的空白以清理它们。答案存储在名为 answer 的变量中,用户的解决方案存储在名为 solution
的变量中演示代码已在 codepen 上运行:
https://codepen.io/codepajamas/pen/zYGMveN?editors=1111
您可以打开控制台查看结果。
以下是 HTML、CSS 和 JavaScript 代码:
<div class="sentence" data-answer="Henry wants to go to the store!">
<span class="sentence-start">Henry</span>
<ul class="words place-words"></ul>
<span class="sentence-end">to the store!</span>
</div>
<ul class="words supply-words"><li class="word">wants </li><li class="word">go </li><li class="word">to </li></ul>
$(function () {
var answer = $('.sentence').data('answer'); // "Henry wants to go to the store!"
$('.words').sortable({
connectWith: '.place-words, .supply-words',
beforeStop: function () {
if ($('.supply-words').text() === '') {
var sentence_start = $('.sentence-start').text(),
placed_words = $('.place-words').text(),
sentence_end = $('.sentence-end').text(),
combined = sentence_start+placed_words+sentence_end,
// get rid of line returns and white space at beginning and end of sentence
solution = combined.replace(/(\r\n|\n|\r)/gm,'').trim();
if (solution === answer) {
console.log('correct');
$('.place-words').removeClass('wrong').addClass('correct');
} else {
console.log('wrong');
$('.place-words').removeClass('correct').addClass('wrong');
}
}// outer if
}// beforeStop function
});
$('.words, .answer').disableSelection();
}; //end document ready
.sentence {
margin: 0 0 10px 0;
}
.words {
display: inline-block;
margin: 0 5px 0 5px;
padding: 0;
width: auto;
min-width: 135px;
height: 30px;
border: 1px dashed #ccc;
vertical-align: bottom;
}
.word {
display: inline-block;
margin: 0;
border: 1px solid #000000;
padding: 5px 10px;
cursor: pointer;
}
.correct {
background: lime;
}
.wrong {
background: pink;
}
如果有人有任何问题,请告诉我。任何帮助表示赞赏。我想我需要用新的眼光来看待这件事。提前致谢!
【问题讨论】:
-
酷应用!当我在比较
console.log(solution, answer);之前登录控制台时,我看到:"Henrywants to go to the store!" "Henry wants to go to the store!"。你能从那里弄清楚吗?
标签: javascript jquery if-statement jquery-ui jquery-ui-sortable