views:

56

answers:

2
$('> img[src="folderopen.gif"]',$scope)

The above will fail,seems a bug of jQuery,is there a work around?

This issue is found here:

http://stackoverflow.com/questions/2062381/how-to-judge-whether-there-is-a-specific-child-haschildtestatttest-wi/2062390#2062390

EDiT

I've just verified this will also fail:

$scope.children( 'img[src="folderopen.gif"]');
+4  A: 

Tested, and Works:

Demo Online: http://jsbin.com/uyuri3

<p id="scope"> 
  <img src="foo.jpg" /> 
</p>

-- with --

$(function(){
  var scope = $("#scope");
  alert( $(scope).children("img[src$='foo.jpg']").attr("src") );
});

-- works with your original syntax too --

var img = $("> img[src$='foo.jpg']", scope);

An Interesting Bug

We know that our src value is foo.jpg, yet the following fails:

$("img[src='foo.jpg']");

So I was curious if jQuery's interpretation of the src would be equal to the string literal source I provided in the HTML:

$("img", scope).attr("src") === "foo.jpg"; // true

This makes the whole situation very strange. jQuery argues that the src value is NOT equal to "foo.jpg" when you pass it in as part of the selector, but it IS equal to the string literal when you compare from a call to attr().

In the end, $= is necessary to get jQuery to agree that "foo.jpg" is equal to "foo.jpg". This certainly is a bug, but not an insurmountable one.

Jonathan Sampson
I've never seen `$=`,what does it mean?
It means the attribute "ends with" a particular value.
Jonathan Sampson
Why is it necessary here?
Apparently the exact value isn't understood to be the exact value by jQuery. Turns out it *is* a bug, but not an insurmountable one. If this helped, please consider accepting.
Jonathan Sampson
Yes,I'll accept your answer plus +1 vote.But I still don't understand why `$=` is necessary here.
unknown, it's very strange. I'm going to add a bit of further discussion to my answer. Keep watching :)
Jonathan Sampson
Oh,seems `$=` will be `true` for `*foo.jpg`,right?
Yes. If it ends with `foo.jpg` (kungfoo.jpg, for example), it evaluates to true.
Jonathan Sampson
I hope this bug will disappear in next release of jQuery.
It is present in 1.4 due to be released today. I'll open a bug report tomorrow.
Doug Neiner
+2  A: 

You should just do:

$(scope).children("img[src='folderopen.gif']");

From that expression I assume you're doing some kind of tree like structure (like Windows Explorer). If so, I'd strongly urge you to instead use classes as markers rather than using attribute selectors, which are slow on most browsers. For example, with this CSS:

ul.tree li { background: url(folderclosed.gif); }
ul.tree li.open { background: url(folderopen.gif); }

you'd then do:

$(scope).children("li.open")...

which will be much faster.

cletus