jQuery if / else with:not not working

时间:2013-04-25 05:27:44

标签: jquery

http://jsfiddle.net/ySLkQ/16/

的jQuery

if ($("h1.change:contains('-')")) {
    $("h1.change").append(" it's negative");
} else if ($("h1.change:not(contains('-'))")) {
    $("h1.change").append(" it's positive");
}

HTML:

<h1 class="change">-30</h1>
<h1 class="change">30</h1>

基本上无论我做什么,最后<h1>总是显示负面

4 个答案:

答案 0 :(得分:3)

您的if仅在ONCE执行。

它检查$(“h1.change:contains(' - ')”)是否计算为true - 它返回一个元素,所以它是真的。

之后,它对所有h1.change元素应用“它为负”。

其他部分永远不会被执行。

$("h1.change").not(":contains('-')").append(" it's positive");
$("h1.change:contains('-')").append(" it's negative");

将按预期工作 - 每个选择器将评估为元素列表,并且append()将在所有元素上执行。

答案 1 :(得分:2)

Arun指出丢失的:,但是you can use jQuery to do this a little more efficiently

var change = $("h1.change"),
    negative = change.filter(":contains('-')"),
    positive = change.not(negative);

// you can do the appends above, but I prefer the clarity
negative.append(" it's negative");
positive.append(" it's positive");

此外,第一个if总是会影响其他change元素。使用上述方法将保留两个专属组。

答案 2 :(得分:1)

使用此

$('h1.change').html(function(val, html){
    return html + ( html.indexOf('-') == -1 ? " it's positive" : " it's negative" )
});

演示:Fiddle

答案 3 :(得分:0)

您也可以通过$.each()功能实现此目的。这样做更好,因为您希望将字符串附加到具有相同选择器条件的多个h1元素。如果您尝试编写单个语句,则可能会导致某些问题,例如在不需要时将相同值写入多个元素。虽然$.each()可能效率不高。 @DThought的答案在效率方面要好得多,你已经接受了答案。

$("h1.change").each(function(index){
    if ($(this).text().indexOf("-")!=-1) {
        $(this).append(" it's negative");
    }else{
        $(this).append(" it's positive");
    }
});
相关问题