I have a for loop and my traces to the console are showing that my variables are correct. epid is determined in another method.
for (var i=0; i< $('#slideshow > div').length; i++) {
var divid = $('#slideshow > div').eq(i);
console.log(divid)
console.log(epid)
if ( divid == epid ) {
alert("equal " + epid);
} else {
console.log("blah");
};
};
At one point in the loop, the console shows that the element is the same, but the alert doesn't pop up. CONSOLE:
<div style="height: 100%; display: none; " id="ep5">…</div>
<div style="height: 100%; display: none; " id="ep6">…</div>
blah
<div style="height: 100%; display: none; " id="ep6">…</div>
<div style="height: 100%; display: none; " id="ep6">…</div>
blah
<div style="height: 100%; display: none; " id="ep7">…</div>
<div style="height: 100%; display: none; " id="ep6">…</div>
blah
divid
is a jQuery object. It will NEVER match another variable unless that variable points at exactly the same jQuery object. ==
or ===
compares object references to see if they are exactly the same object. It does not compare the contents of those objects.
If epid is a DOM object and the point of your code is to to compare DOM objects, then you should use .get(i)
or [i]
instead of .eq(i)
for both epid
and divid
:
var divid = $('#slideshow > div').get(i);
Assuming epid
is a DOM object and you're looking for which item in your slideshow matches that object, you can have much more efficient and correct code like this:
var items = $('#slideshow > div');
for (var i = 0; i < items.length; i++) {
var divid = items[i];
if ( divid === epid ) {
alert("equal " + epid);
} else {
console.log("blah");
}
}
If, you just want to know what index epid
is in the slideshow collection, you don't need a for
loop to manually find it - you can do that like this:
var index = $('#slideshow > div').index(epid);
I assume from your code you want to compare the Html of the elements?
for (var i=0; i< $('#slideshow > div').length; i++) {
var divid = $('#slideshow > div').eq(i);
console.log(divid)
console.log(epid)
if ( divid.html() == epid.html()) {
alert("equal " + epid);
} else {
console.log("blah");
};
};
You are comparing two objects here .. It will only be true if is exactly the same object.. SO instead of == use === . Also lets assume that if each div has an id you can compare the id attribute of it..
for (var i=0; i< $('#slideshow > div').length; i++) {
var divid = $('#slideshow > div').eq(i);
var dID = divid.attr('id');
var eID = epid.attr('id');
console.log(divid);
console.log(epid);
if(dID != '' && eID != ''){
if ( dID == eID ) {
alert("equal " + epid);
} else {
console.log("blah");
};
}
};
This will only work if the div already has a ID for it.. Or a class that is specific for each div..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.