开发者

jquery writing an if

I have some code like this:

if (开发者_运维技巧$(event.target).is('.class1') || $(event.target).is('.blab') || $(event.target).is('.foo') || $(event.target).is('.cbncvbn') || $(event.target).is('.dfghdfgh') || $(event.target).is('.tryrty')) {
    // Do something
}

Is there a more succinct way to write this?

PS: I know there are better ways to do the same thing, but this question is about the syntax of the conditions.

Thanks.


Well, jQuery uses CSS3 selectors you can just as well do this:

if ($(event.target).is('.class1, .blab, .foo, .cbncvbn, .dfghdfgh, .tryrty')) {
    // Do something
}

The match applies to any, as it does with CSS rules


In theory hasClass would be the most appropriate way to test whether an element has a given class name. However jQuery itself implements hasClass like this:

this.is( "." + selector )

which is not only just the same code in the end, but also breaks badly if you have a class name containing punctuation with a meaning in selectors. Bad jQuery, no cake!

So I'd stick with Paolo's answer. If performance is an issue the speed could be improved by using plain JavaScript to split the className list just once. But probably it won't matter in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜