3

我正在尝试制作一个 if 语句,如果按钮的父级是其父级的偶数子级,则 do alert("it works");, else do alert("nope");,这可能很容易,我对此很陌生!:) 这是我当前的代码:

HTML:

<div>
    <div>
        <button>#0</button>
    </div>
    <div>
        <button>#1</button>
    </div>
    <div>
        <button>#2</button>
    </div>
    <div>
        <button>#3</button>
    </div>
</div>​

JS:

$(function () {
        $("button").click(function () {
            var $parent = $(this).parent();
            if ($parent.is(":even")) {
                alert("it works");
            } else {
                alert("nope");
            }
        });
});​

jsFiddle:http: //jsfiddle.net/goldson/Rn6gz/1/

提前致谢!

4

2 回答 2

6

您可以使用index()来获取索引并使用模运算符%来知道它是event还是odd

现场演示

$(function () {
    $("button").click(function () {
        var $parent = $(this).parent();
        if ($parent.index() % 2 == 0) {
            alert("it works");
        } else {
            alert("nope");
        }
    });
});​
于 2012-12-14T11:54:36.107 回答
3

一种解决方法是将类添加到您的偶数 div 元素:

演示

<div id="parentDiv">
    <div>
        <button>#0</button>
    </div>
    <div>
        <button>#1</button>
    </div>
    <div>
        <button>#2</button>
    </div>
    <div>
        <button>#3</button>
    </div>
</div>


$(function () {

    var arr = $('#parentDiv div');
    arr.filter(":even").addClass("even");

    $("button").click(function () {
        var $parent = $(this).parent();
        if ($parent.is(".even")) {
            alert("it works");
        } else {
            alert("nope");
        }
    });

});

于 2012-12-14T11:57:56.987 回答