开发者

JavaScript/jQuery "if" condition syntax

I'm attempting to evaluate a class to see if it contains some text in my cl开发者_开发百科ick handler, but I can't get my code to act properly. What am I missing?

The if statement is looking to see whether the class of the clicked object has the word "headline" in it.

$('[class^=edit_]').click(function(){
    var element = $(this).attr('class');
    var field = element.split(/_(.+)/)[1];
    if ($(this).attr('[class*=headline]'))
    {
        alert("headline");
    }
    else
    {
        alert("not headline");
    };
});

Is it possible to construct my if statement with something that evaluates the var field = element.split(/_(.+)/)[1]; since that is really where the information resides.

Something like:

if (element *= "headline"){do this};

I'm not sure I understand all of the "evaluators" that exist in JavaScript to know if I can evaluate a string like that.


Upon re-reading your question, there's an even simpler approach, just check the .className for the string you want using .indexOf(), like this:

if (this.className.indexOf('headline') != -1)

Previous answer:
The closest version to what you have, checking if an element matching a selector is .is(), like this:

if ($(this).is('[class*=headline]'))

But there's another method more appropriate here (if you're checking for a full class, not part of one), you can use .hasClass() like this:

if ($(this).hasClass('headline'))
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜