First of all, after "testing" a while I have to say, stackoverflow is really really cool!
To my question: I want to check if $(this) has not any parents that have a class or id specified in an js-array.
By now I did this with "eval", but Andy E. ju开发者_如何转开发st convinced me, that it is better to abandon "eval". However I have no clue how to do it in this case.
Here is pretty much of what I did:
var testthis = '!(($(this).parents("'+<MY_ARRAY>.join('").length > 0 || $(this).parents("')+'").length > 0)';
if (eval(testthis)) {
....
}
If anybody is kind enough to answer my question, I have to appologize that I cannot read (and comment or rate) his/her answer in the next few hours. Sorry!
Try this, no eval needed:
if(!$(this).parents(<MY_ARRAY>.join(', ')).length) {
//elem has none of those parents
}
MY_ARRY in this case contains things like ".class1", ".class2", "#id1", "#id2"
Alternatively slower but yo can check for both cases if the array is just strings:
if(!$(this).parents("." + <MY_ARRAY>.join(', .')).length &&
!$(this).parents("#" + <MY_ARRAY>.join(', #')).length) {
//elem has none of those parents
}
MY_ARRY in this case contains things like "class1", "class2", "id1", "id2", but IDs could match like #class1 could be a match, so this is less desirable.
Well you could iterate through the nodes for $(this) assuming there are more than one, check the parents by walking up the tree to each one, caching any paths you have already walked up, but really I think whatever you are trying to do here, there's probably a better way.
精彩评论