0

我想在用户单击链接时将标记字符添加到链接,并在他第二次单击链接时将其删除。

这是我所拥有的:

$('#text a').click(function () {
    $(this).addClass('clicked');
    $(this).text(markerTextChar +  $(this).text());
    $(this).click(function () {
        $(this).removeClass('clicked');
        $(this).text($(this).text().substring(1));
    });
});

标记是在单击时添加的,但是当我单击它以取消选择它时又添加了一次。

你能帮我解决这个问题吗?

4

2 回答 2

1

Adding a event handler with bind (or click) doesn't remove the old ones.

You could unbind it but this is not needed. Do this instead :

$('#text a').click(function () {
   if ($(this).hasClass('clicked')) {
        $(this).removeClass('clicked');
        $(this).text($(this).text().substring(1));
   } else {
      $(this).text(markerTextChar +  $(this).text());
       $(this).addClass('clicked');
   } 
});

demonstration


You might also use toggleClass and use :before in css to add your char, that would be much cleaner.

css :

.clicked:before {
    content: "yourmarker";
}​

javascript :

$('#text a').click(function () {
   $(this).toggleClass('clicked');
});​

demonstration

于 2012-10-16T11:08:50.083 回答
0

you have to unbind first click event do it like this

$('#text a').click(function () {
    $(this).addClass('clicked');
    $(this).text(markerTextChar +  $(this).text());
    $(this).removeAttr('onclick');
    $(this).click(function () {
        $(this).removeClass('clicked');
        $(this).text($(this).text().substring(1));
    });
});
于 2012-10-16T11:09:01.630 回答