0

I'm using jquery to remove and add some class to a element as shown below

$("#"+obj.id+" div.treeclick").removeClass("ui-icon-radio-off").removeClass("tree-leaf").addClass("tree-minus").addClass("ui-icon-triangle-1-s");

now I want to bind events that are there for class tree-minus so I use the following line

$("#"+obj.id+" div.treeclick").removeClass("ui-icon-radio-off").removeClass("tree-leaf").addClass("tree-minus").addClass("ui-icon-triangle-1-s").bind($(".tree-minus").data('events'));

but I got an error saying " Object has no method 'apply' " ,how can I add events that I'll get from $("tree-minus").data('events')

Thanks in advance

4

1 回答 1

0
$("#" + obj.id + " div.treeclick")
    .removeClass("ui-icon-radio-off tree-leaf")
    .addClass("tree-minus ui-icon-triangle-1-s");

$("#" + obj.id).on($(this).data('events'), 'div.treeclick', function() {

});

或者

   $("#" + obj.id + " div.treeclick")
        .removeClass("ui-icon-radio-off tree-leaf")
        .addClass("tree-minus ui-icon-triangle-1-s")
        .on($(this).data('events'), 'div.treeclick', function() {
            alert('event binded');
        });

笔记

您不需要为每个类单独调用addClass()removeClass(),只需使用逗号分隔值。

为什么需要.on()委托事件

因为,当您更改元素的类时,它会将其视为新元素,而不是以前存在于 DOM 中,因此它需要委托事件。


根据你的评论

$("#" + obj.id + " div.treeclick")
    .removeClass("ui-icon-radio-off tree-leaf")
    .addClass("tree-minus ui-icon-triangle-1-s");

$("#" + obj.id).on($('.tree-minus').data('events'), '.tree-minus.ui-icon-triangle-1-s', function() {

});
​
于 2012-06-07T06:50:23.363 回答