如果单击复选框,则使用AEMS中的Javascript添加类
我试图在AEM组件内的div中定位一个名为“水平视频”的类,如果作者单击了一个ID为“coral-ID-540”的复选框,我想在该div中添加第二个名为“flipped”的类。以下是我编写的代码,它不起作用。有人能帮我弄清楚为什么它不起作用吗?控制台不显示错误如果单击复选框,则使用AEMS中的Javascript添加类,javascript,jquery,aem,Javascript,Jquery,Aem,我试图在AEM组件内的div中定位一个名为“水平视频”的类,如果作者单击了一个ID为“coral-ID-540”的复选框,我想在该div中添加第二个名为“flipped”的类。以下是我编写的代码,它不起作用。有人能帮我弄清楚为什么它不起作用吗?控制台不显示错误 var x = document.getElementsByClassName("horizontal-video"); $('#coral-id-540').change(function(){ if($(this).is("
var x = document.getElementsByClassName("horizontal-video");
$('#coral-id-540').change(function(){
if($(this).is(":checked")) {
$(this).addClass("flipped");
} else {
$(this).removeClass("flipped");
}
});
很可能您没有等待DOM完全加载,或者在页面加载期间,至少在页面上有问题的元素下面有这段代码 您的代码是否包装在$document.readyfunction{//your code};中 另外,请注意,任何在页面加载后由JavaScript/jQuery动态添加到页面的元素都不会使用您正在使用的方法附加侦听器 要允许在侦听器中包含动态添加的元素,您应该以祖先节点为目标,并将侦听器添加到该节点。简单英语:将听者附加到更高的元素。最安全但最慢的节点是文档本身,但最好针对更接近的节点:
$(document).ready(function () {
var $horizontalVideo = $(".horizontal-video"); //You're using jQuery - why not use it here? Also, I always name jQuery objects with a `$` in front as a shorthand to know it's wrapped in a jQuery object. Plus, a more descriptive name will help you immensely.
//replace parent-of-coral with the ID of a parent element that you know exists on DOM ready:
$("#parent-of-coral").on("change", "#coral-id-540", function (e) { //get used to using "e" as the event variable for preventing default / stopping propagation / etc
$this = $(this); //cache $(this) reference rather than creating another jQuery object each time you use it
if ($this.is(":checked")) {
$this.addClass("flipped");
} else {
$this.removeClass("flipped");
}
});
});