gpt4 book ai didi

Javascript 循环遍历事件内的数组

转载 作者:行者123 更新时间:2023-12-03 04:49:45 26 4
gpt4 key购买 nike

我正在尝试干燥这段代码,特别是在我想要循环(或增加数字)的 if/else 语句中手动键入 elems 选项。我尝试过使用各种循环,但无法让它在 .change() 事件内工作。

var radioSelect = $("input[type='radio']");
var elems = ["q1","q2","q3","q4","q5","q6"];

radioSelect.change(function () {

// grab the name and value selected radio
// set localstorage
var linkName = $(this).attr('name');
var value = $(this).val();
localStorage.setItem(linkName, value);

// I am trying to loop/increment both through the elements
// and also through the #response[x] divs.
if (link_name === elems[1])
{
$("#response1").html(localStorage.getItem(linkName));
}
else if (link_name === elems[2])
{
$("#response2").html(localStorage.getItem(linkName));
}
else if (link_name === elems[3]) {
$("#response3").html(localStorage.getItem(linkName));
}
});

基本 HTML

<input type="radio" name="q2" value="Yes">
<input type="radio" name="q2" value="No">

最佳答案

您可以将 if/else 替换为 for 循环,如下所示:

var radioSelect = $("input[type='radio']");
var elems = ["q1","q2","q3","q4","q5","q6"];

radioSelect.change(function () {

// grab the name and value selected radio
// set localstorage
var linkName = $(this).attr('name');
var value = $(this).val();
localStorage.setItem(linkName, value);

// I am trying to loop/increment both through the elements
// and also through the #response[x] divs.
for( var i=1; i<=elem.length; i++){
if (link_name === elems[i]){
$("#response"+i).html(localStorage.getItem(linkName));
break;
}
}
});

关于Javascript 循环遍历事件内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42709804/

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