admin管理员组

文章数量:1323323

How would I make sure that this href element is will fire "click" event unless it does NOT have "disablelink" class.

DO NOT PROCESS:

<a class="iconGear download disablelink" href="#">Download</a>

PROCESS:

<a class="iconGear download" href="#">Download</a>

tried this without success:

    $("a.download").not(".disablelink").click(function (e) {
        alert('in');
        e.preventDefault();
    });

How would I make sure that this href element is will fire "click" event unless it does NOT have "disablelink" class.

DO NOT PROCESS:

<a class="iconGear download disablelink" href="#">Download</a>

PROCESS:

<a class="iconGear download" href="#">Download</a>

tried this without success:

    $("a.download").not(".disablelink").click(function (e) {
        alert('in');
        e.preventDefault();
    });
Share asked Nov 6, 2012 at 13:46 ShaneKmShaneKm 21.4k46 gold badges176 silver badges307 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 6

This should work:

$("a.download:not('.disablelink')").click(function (e) {
    alert('in');
    e.preventDefault();
});

If the disablelink class is being added dynamically:

$(document).on('click', "a.download:not('.disablelink')", function (e) {
    alert('in');
    e.preventDefault();
});

Check this demo: http://jsfiddle/d3rXr/1/

$('a.download').click(function(e){
    e.preventDefault();
    if($(this).hasClass('disablelink')){
        return;
    }else{
      //other stuff;
    }
});

Why don't you check when the anchor is clicked, and if it has the class it returns and does nothing, which would be more readable code I guess.

You could go like this:

$("a.download").click(function(e) {
    if($(this).hasClass("disablelink")) {
        return false;
    }
    // Normal code
    alert('in');
    e.preventDefault();
});

Firstly, this probably doesn't work because some links had disablelink added to them dynamically, and after they already had the click handler bound to them.

Secondly, you should just check for that class inside the click handler, like so:

$("a.download").click(function (e) {
    if($(this).hasClass('disablelink')){
       e.preventDefault();
       // link is disabled
    }else{
       alert('in');
       // link is active
    } 
});

本文标签: javascriptjquery click event on element not having a classStack Overflow