我有一个 key ,val dict
像这样:
choices = {'first': 1, 'second': 2, 'third': 3}
然后一组像这样的div:
<div class="choice_result">
<p class="choice_result_text">first<p/>
<span></span>
</div>
<div class="choice_result">
<p class="choice_result_text">second<p/>
<span></span>
</div>
<div class="choice_result">
<p class="choice_result_text">third<p/>
<span></span>
</div>
我想遍历每个 .choice_result_text
,如果 .choice_result_text
== key
,我想更改它的 html span
到 val
。现在,我的 jQuery 代码(在 ajax 成功函数中)如下所示:
result = $('.choice_result_text');
$.each(data.choices, function (key, val) {
$.each(result, function () {
if(result.html() == key) {
j = $('.choice_result').find('span').html(key);
j.html(val);
}
})
});
现在,此代码将每个 span
转换为选择中的第一个 val
(1
)。知道如何让它正常工作吗?
最佳答案
一些问题
您的 HTML 有
<p/>
这不是结束标签,而是打开新p
的标签元素。您应该将其更改为</p>
遍历
choices
是浪费时间属性,当对象属性的优点是您可以直接访问它们时,无需循环。所以跳过外层循环,在内层循环中找到对象值(不需要额外的循环)不要使用
.html()
当您使用纯文本时。有一个单独的方法:.text()
.$('.choice_result').find('span')
会找到所有span
具有给定类的祖先的标签。相反,您应该使用已经通过each
做出的选择的当前上下文。 . jQuery 集this
到匹配的元素,并使用next
你可以找到下一个 sibling 。您可以使用
$(selector).each(...)
而不是$.each($(selector),...)
我认为这更具可读性。
这是一个可以完成这项工作的版本:
var choices = { first: 1, second: 2, third: 3 };
$('.choice_result_text').each(function () {
var key = $(this).text();
if (key in choices) {
$(this).next('span').text(choices[key]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="choice_result">
<p class="choice_result_text">first</p>
<span></span>
</div>
<div class="choice_result">
<p class="choice_result_text">second</p>
<span></span>
</div>
<div class="choice_result">
<p class="choice_result_text">third</p>
<span></span>
</div>
关于javascript - 尝试遍历键、值字典,并将键与另一个 for 循环匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42175988/