【问题标题】:Javascript in AEMto add a class if a checkbox is clicked如果单击复选框,AEM 中的 Javascript 将添加一个类
【发布时间】:2019-09-30 17:15:26
【问题描述】:
我试图在 AEM 组件内的 div 中定位一个名为“horizontal-video”的类,如果作者单击了 ID 为“coral-id-540”的复选框,我想添加第二个类称为“翻转”到 div。这是我编写的不起作用的代码。有人可以帮我弄清楚为什么它不起作用吗?控制台不显示错误。
var x = document.getElementsByClassName("horizontal-video");
$('#coral-id-540').change(function(){
if($(this).is(":checked")) {
$(this).addClass("flipped");
} else {
$(this).removeClass("flipped");
}
});
【问题讨论】:
标签:
javascript
jquery
aem
【解决方案1】:
很有可能您没有等待 DOM 完全加载,(或者至少在页面加载期间页面上相关元素下方有这段代码)
您的代码是否包含在 $(document).ready(function(){ //your code }); 中?
另外,请注意,在页面加载后通过 JavaScript/jQuery 动态添加到页面的任何元素都不会使用您正在使用的方法附加侦听器。
要允许动态添加的元素包含在您的侦听器中,您应该定位一个祖先节点并将侦听器添加到该节点。用简单的英语:将听众附加到“更高”的元素。最安全(虽然最慢)的节点是 document 本身,但最好定位更近的节点:
$(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");
}
});
});