在单击jquery上将类添加到父级

时间:2015-09-02 08:45:11

标签: jquery

这个脚本应该这样做:

  var  link = $("a"),
    rate = $('<div><a href="" class="fa fa-check-circle good"></a><a href="" class="fa fa-times-circle bad"></a></div>'),
    good = $(".good"),
    wrong = $(".bad");
    good.on("click", function() {
        $(this).closest("th").addClass("good");
    });
    wrong.on("click", function() {
        $(this).closest("th").addClass("verybad");
    });
  • 如果我点击显示带有两个元素的div

  • 如果我点击元素,例如使用类.good,它应该添加父.good类。

您可以找到整个代码here

1 个答案:

答案 0 :(得分:2)

使用事件委托(因为您动态追加.good.bad DOM元素):

$(document).on("click", "a", function(e) {
    e.preventDefault();
});
$(document).on("click", ".good", function() {
    $(this).closest("th").addClass("good");
});
$(document).on("click", ".bad", function() {
    $(this).closest("th").addClass("verybad");
});

另外,你的CSS中有一个拼写错误,应该是:

.verybad { /* note the "y" you missed */
    color:  #e07ccd;
}

最后,如果存储jQuery对象以获得更好的可读性,请习惯prepending your variable names by $

JSFiddle

相关问题