如何结合 .change
的这两种不同用途做一个功能?
两者都在使用$('input[name="menu"]')
但在语义上不同,所以我不确定将两者结合起来的正确方法。
我尝试输入 $(".menu[data-id=" + this.id + "]").toggleClass("active", this.checked);
.on("change"), function ()
里面没有任何运气。
$('input[name="menu"]')
.change(function() {
$(".menu[data-id=" + this.id + "]").toggleClass("active", this.checked);
})
.change();
$(function() {
$('input[name="menu"]').on("change", function() {
if (
$(this)
.closest('[class*="list-"]')
.is(".list-custom")
) {
if ($(this).is(":checked")) {
$(this)
.siblings("[data-icon]")
.attr("data-prefix", "fas")
.closest(".launch-icon")
.addClass("checked");
} else {
$(this)
.siblings("[data-icon]")
.attr("data-prefix", "far")
.closest(".launch-icon")
.removeClass("checked");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
最佳答案
如果是我,我会像这样合并您的代码,但如果您正在寻找问题的真正解决方案,请包含 html 标记和有效的代码片段。
// Starting point.
$(document).ready(function()
{
// Register listener for the change event.
$('input[name="menu"]').change(function()
{
// This was on the first listener of change event.
$(".menu[data-id=" + this.id + "]").toggleClass("active", this.checked);
// This was on the second listener of change event.
if ($(this).closest('[class*="list-"]').is(".list-custom"))
{
if ($(this).is(":checked"))
{
$(this).siblings("[data-icon]").attr("data-prefix", "fas")
.closest(".launch-icon").addClass("checked");
}
else
{
$(this).siblings("[data-icon]").attr("data-prefix", "far")
.closest(".launch-icon").removeClass("checked");
}
}
});
// Trigger a change event on the input element.
// This was after the first event listener (why?)
$('input[name="menu"]').change();
});
关于javascript - 组合两个更改功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712126/