javascript - 选中复选框时添加类并更改内部 HTML

标签 javascript jquery html css checkbox

我想在上面的 div 中添加/删除一个类 "related-box-check" 并在选中复选框时更改标签的内部 HTML。当再次取消选中该框时,应将其删除(恢复为默认值)。我的复选框 ID 是动态生成的。

我怎样才能做到这一点?

我的 HTML 看起来像这样:

<div class="related-box-check">
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox162569" name="related_products[]" value="162569">
<label class="label-related" for="related-checkbox162569">Add for check</label>
</div>

JSFiddle:https://jsfiddle.net/ws7wk19g/

最佳答案

这会做你需要的...

$(function() {  // document.ready handler

  $("input[type=checkbox]").on("change", function() {
    if (this.checked) {
      $(this)
        .closest(".related-box-check")
        .addClass("new-class")
        .find(".label-related").each(function() {
          var $this = $(this);
          $this.data("original-inner-html", $this.html());
          $this.html("Some new text because you checked the box!");
        });
    }
    else {
      $(this)
        .closest(".related-box-check")
        .removeClass("new-class")
        .find(".label-related").each(function() {
          var $this = $(this);
          var original = $this.data("original-inner-html");
          $this.html(original);
        });
    }
  });

});

它找到每个复选框并添加一个更改事件处理程序,每次复选框值更改时都会执行该事件处理程序。选中时,代码会找到最近的类.related-box-check(父div)的父元素并添加类new-class,然后更改标签的 html(存储原始值后)。然后,当您取消选中该复选框时,它会撤消所有这些操作 - 将标签设置回其原始值并删除添加的类。

这是一个更新的 jsfiddle,展示了它的实际应用...

https://jsfiddle.net/ws7wk19g/9/

关于javascript - 选中复选框时添加类并更改内部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42767416/

相关文章:

javascript - Passport.js 执行

javascript - 如何在两个div之间画一条线?

javascript - 使用类检查文本框中的值是否已更改

c# - 在 Azure 中发布时 Web 应用程序行为不同

html - 为什么我不能水平和垂直居中我的 div?

javascript - 构造函数中未定义数组,类型错误 : Cannot read property '0' of undefined

jquery - css中的动画延迟

jquery - ASP.NET MVC + JQuery Mobile 事件处理程序

html - jqplot 图形背景在 ie8 中似乎是黑色的

html - 具有固定定位和 float 的 div