gpt4 book ai didi

javascript - 使用 id 'user' +i 的复选框切换 id 'checkbox' +i 的属性

转载 作者:行者123 更新时间:2023-11-28 04:41:53 27 4
gpt4 key购买 nike

首先感谢您提前提供的帮助。我在 jquery 和 javascript 方面是个新手,而且我不太会说英语,所以我在我的研究中找不到任何喜欢的东西。

这是我的html

<li></li>
<li></li>
<li id="user1"></li>
<input type="checkbox" id="checkbox1">

<li></li>
<li></li>
<li id="user2"></li>
<input type="checkbox" id="checkbox2">

我想每次选中带有 id 的复选框(“checkbox”+i)时,我都会在(“user”+i)中切换一个类以插入列表,然后通过发布请求发送。

我试过了

for(i = 1; i < 3; i++) {    
document.getElementById('checkbox' + i).addEventListener('change', function() {
document.getElementById('user' + i).setAttribute("class", "passInterestIds");
});
}

但它只给我 user3 独立于复选框

我怎样才能做到这一点?

最佳答案

因此,只要 id 包含一位数字,这将始终有效,因为我们从匹配函数中获取的内容。然后,如果选中复选框,则添加类 hello,否则删除类 hello

var elements = $('input[type^=checkbox');
elements.on('click', function(){
var idNr = $(this).attr('id').match(/\d+/)[0];
if($(this).is(':checked')) {
$('#user' + idNr).addClass('hello');
} else {
$('#user' + idNr).removeClass('hello');
}
});
.hello {
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li id="user1"></li>
<input type="checkbox" id="checkbox1">

<li id="user2"></li>
<input type="checkbox" id="checkbox2">

如果可以更改 HTML.. 更好的方法是使用包含数字的输入元素中的 value 属性。或者,如果无法使用 value 属性,请使用 data-user-id 属性。

var elements = $('input[type^=checkbox');
elements.on('click', function(){
var idNr = $(this).val();
if($(this).is(':checked')) {
$('#user' + idNr).addClass('hello');
} else {
$('#user' + idNr).removeClass('hello');
}
});
.hello {
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li id="user1"></li>
<input type="checkbox" id="checkbox1" value="1">

<li id="user2"></li>
<input type="checkbox" id="checkbox2" value="2">

关于javascript - 使用 id 'user' +i 的复选框切换 id 'checkbox' +i 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43688585/

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