gpt4 book ai didi

javascript - 在 div/class 数组中查找特定键

转载 作者:行者123 更新时间:2023-11-30 05:40:26 25 4
gpt4 key购买 nike

我将 javascript 数组中的单词附加到 div 类 bank-word,它将所有单词添加到用户的单词库中:

for (obj in words) {
for (key in words[obj]) {
$(".wordBank_Words").append("<div class='bank-word' word='" + key + "' ><b>" + key + "</b>: " + words[obj][key] + "</li>");
}
}

如果用户点击词库中的一个词,它会将该词添加到一个文本框中,并从词库中隐藏它:

enter image description here

$(".bank-word").click(function (event) {

//append each newly selected word to text box
$('#textBox').val($('#textBox').val() + " " + $(this).attr('word'));

//hide word from word bank
$(this).hide();

然后,如果用户从文本框中删除了该词,我希望该词作为选项重新出现在词库中。这是我遇到麻烦的部分。我可以使用 isInArray(key, array) 检查该词是否不再存在于文本框数组中,但是我无法检查词库以查看它是否还不存在于使用 isInWordBank(key) 的词库(意思是,用户已经选择了之前的词,因此从词库中隐藏了它)。现在它需要重新出现在词库中,因为它已从文本框中删除。

我的问题是,如何使用 jQuery.inArray 传递我要查找的词以及包含该词的 div 类数组。我认为它会是 jQuery.inArray(word, $(".wordBank_Words"))。我以为我可以将 jQuery find()each() 一起使用,但这不会让我从 div 类中获取特定的键。

for (obj in words) {
for (key in words[obj]) {

//if word doesn't exist in text box array, and doesn't exist in word bank, add it back to word bank
if (!isInArray(key, array) && !isInWordBank(key)) {
log(key + " doesn't exist in text box array or word bank");
//add word back to word bank
}
}
}

检查单词是否在文本框数组中:

function isInArray(word, array) {
return array.indexOf(word) > -1;
}

应该检查单词是否在单词库中:

function isInWordBank(word) {
//search through word bank for key
jQuery.inArray(word, $(".wordBank_Words"))
}

HTML:

<input type="text" id="textBox"  value="" />
<br/>
<button onclick="submitMe()" id="testButton" >Submit Response </button>
<br/>

<div class="wordBank_Headings">Word Bank:
<span class="wordBank_Words"></span>
</div>

最佳答案

我在解析你的代码时遇到了一些麻烦,但我认为你想要的是这样的:

$('#textBox').on('change', function(){

var words = $(this).val().split(' ');

$('.bank-word').each(function(){

if( words.indexOf( $(this).attr('word') ) !== -1 ){
$(this).hide();
}

else {
$(this).show();
}

});

});

这对您要实现的目标有用吗?

关于javascript - 在 div/class 数组中查找特定键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21083582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com