문제

Why can't I change the CSS of an a tag with jquery? For instance,

html,

<a href="#">1</a>
<a href="">2</a>
<a href="http://website.com/#/home/about/">3</a>
<a href="http://website.com/home/about/">4</a>

link 1 and 2 are not clickable so I want to remove the pointer cursor.

jquery,

$("a").click(function(e){
    if($(this).attr("href") == "#" || $(this).attr("href") == "") {
        alert("this is non-clickable");
        $(this).css({cursor:"default"});
        e.preventDefault();   
    }
    else{
        alert($(this).attr("href"));
        $(this).css({cursor:"pointer"});
        e.preventDefault();   
    }
});

is it possible?

jsfiddle

도움이 되었습니까?

해결책

If you want you can simply do this with the CSS

a[href="\#"], a[href=""] {
    cursor: default;
}
/* I've used an element[attr] selector here which will select all a tags 
   with this combination, if you want to target specific a tags, 
   wrap them in an element with a class and you can than refer as 
   .class a[href]... */

Demo

If you want to disable the links, you can achieve that too using CSS pointer-events: none; property

Demo 2 (Will help you if JS is disabled, this won't alert the message, but it will help you to disable the event which you are trying to do)

다른 팁

Your error is in your jquery css. You need quotes round css your js should look like this:

$("a").click(function(e){
    if($(this).attr("href") == "#" || $(this).attr("href") == "") {
        alert("this is non-clickable");
        $(this).css({'cursor' :"default"});
        e.preventDefault();   
    }
    else{
        alert($(this).attr("href"));
        $(this).css({'cursor':"pointer"});
        e.preventDefault();   
    }
});

Also you could use addClass method then in the css have a style for no href

try to change the line

form

$(this).css({cursor:"default"});

to

$(this).css('cursor','default');

let me know if you face any problem

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top