Error choosing jQuery 1.7

This is my first question.

I am working on a fully Ajax system with jQuery and it works fine with 1.6.2. When I tried to upgrade it to 1.7, this part of the code stopped working properly:

$("a[class!='']").live("click",function(e){ e.preventDefault(); }); 

In 1.6.2, it prohibits all hyperlink tags from working as a link if they have a class, but in 1.7 it stopped ALL links from working as real links, even those who don't have classes.

Fiddle: http://jsfiddle.net/hBehg/

+6
source share
4 answers

Use $('a[class]') , this will select all elements that have a class attribute. As I said in my comment, checking for an empty value may not work if the element does not have a class attribute.

Update: As @Sidnicious pointed out , the documentation says that this selector will also select those elements that do not have this attribute. If it was not in version 1.6, then it was actually a mistake in this version, or they changed the description. without mentioning it.

Of course, if you really have an empty class attribute, i.e. <a class=""> , this will not work.

Demo

Update 2: As @lonesomeday mentions in his comment, $('a[class][class!=""]') Works the way you planned with $(a[class!=""]) .

As already mentioned, you can change to on in jQuery 1.7, which unifies event handling methods, but it will not solve your specific problem.

+6
source

JQuery docs describe the [name! = Value] selector as follows:

Select items that either do not have a specified attribute or that have a specified attribute but do not have a specific value.

In your case, it will select every a that does not have a class or whose class is not equal to the empty string. <a></a> and <a class=""></a> do not match.

It could be a bug in jQuery 1.6!

+3
source

You can use .filter to get the desired result in jQuery 1.7:

 $('a').filter('[class]').on("click",function(e){ e.preventDefault(); }); 

http://jsfiddle.net/mblase75/hBehg/1/

If you replace .on with .live , it no longer works correctly:

http://jsfiddle.net/mblase75/hBehg/4/

Although .bind works fine:

http://jsfiddle.net/mblase75/hBehg/5/

+1
source

Try to execute

 $("a").live("click",function(e){ if ($(this).attr('class') === undefined) { e.preventDefault(); } }); 

I checked this on 1.7 and 1.6.4. It is less ideal than a selector that includes a predicate, but it will do its job.

+1
source

Source: https://habr.com/ru/post/901042/


All Articles