我在 ASP.NET 中使用 CheckBoxList 应用程序:
<asp:CheckBoxList runat="server" ID="myCheckBoxList">
<asp:ListItem Text="1 16" />
<asp:ListItem Text="1 17" />
<asp:ListItem Text="2 20" />
</asp:CheckBoxList>
我想在单击按钮后更改所选元素的样式。为此,我有 JavaScript 功能:
function changeColor() {
var checkBoxList = document.getElementById("myCheckBoxList");
var options = checkBoxList.getElementsByTagName('input');
for (var i = 0; i < options.length; i++) {
console.log(options[i].checked);
if (options[i].checked) {
options[i].parentElement.className = 'Red';
}
}
}
当我单击按钮时,所选元素会在很短的时间内(大约 0.5 秒)改变颜色,然后恢复为默认的黑色。为什么我的复选框列表项样式重置?我不想要这种行为。如何更改我的代码以永久更改颜色(不仅仅是 0.5 秒)?
最佳答案
这里是完整的解决方案:
<script type="text/javascript">
function changeColor() {
var checkBoxList = $('[id$="myCheckBoxList"]');
var options = checkBoxList[0].getElementsByTagName('input');
for (var i = 0; i < options.length; i++) {
console.log(options[i].checked);
if (options[i].checked) {
options[i].parentElement.className = 'Red';
}
}
return false;
}
</script>
<asp:CheckBoxList runat="server" ID="myCheckBoxList">
<asp:ListItem Text="1 16" />
<asp:ListItem Text="1 17" />
<asp:ListItem Text="2 20" />
</asp:CheckBoxList>
<asp:Button OnClientClick="return changeColor();" Text="Test" runat="server" />
我已经使用 jQuery 本地化了 myCheckBoxList,因为如果您使用母版页,它在浏览器中可能有不同的 ID。其次,我从函数返回 false 以防止在按钮单击时回发以维护类值。
关于javascript - 更改 CheckBoxList 元素样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36129717/