0

この単純な if/else を機能させるのに少し問題があります。

$(document).ready(function () {
    $(".sme").click(function (event) {

        var vote = $(this).attr('id');
        $('.to').html(vote);

        $(".sme").removeClass('clicked');
        $(this).addClass('clicked');
    });
});


$(document).ready(function () {
    $(".tme").click(function (event) {

        var more = $(this).attr('id');
        $('.more').html(more);


        if (typeof vote) {

            $('.error').html("ERRRROOORRRR");

        } else {

            $(".tme").removeClass('clicked');
            $(this).addClass('clicked');

        }

    });
});

if/else の動作に問題があります。

どんな助けでも素晴らしいでしょう、ありがとう!

4

2 に答える 2

2

voteundefinedのクリック ハンドラ関数で範囲指定されていないため、常に になります.tme。私はあなたがこのようなものが欲しいと思います:

$(document).ready(function () {
    var vote = undefined;

    $(".sme").click(function (event) {

        vote = $(this).attr('id');
        $('.to').html(vote);

        $(".sme").removeClass('clicked');
        $(this).addClass('clicked');
    });

    $(".tme").click(function (event) {

        var more = $(this).attr('id');
        $('.more').html(more);


        if (vote === undefined) {

            $('.error').html("ERRRROOORRRR");

        } else {

            $(".tme").removeClass('clicked');
            $(this).addClass('clicked');

        }

    });
});
于 2013-05-31T01:04:21.267 に答える
1

voteclickイベント ハンドラのローカル変数です。別のイベント ハンドラー内で呼び出すことはできません。存在しません。

なぜ 2 つのdocument readyハンドラを使用しているのですか? 1つだけ使用してください。私はこのようなことをします:

<script type="text/javascript">
$(document).ready(function() {
    $(".sme").click(function (event) {

        window.vote = $(this).attr('id');
        $('.to').html(window.vote);

        $(".sme").removeClass('clicked');
        $(this).addClass('clicked');
    });

    $(".tme").click(function (event) {

        var more = $(this).attr('id');
        $('.more').html(more);

        // Two cases. If it's undefined will throw error. The same if it is a string, but its length equals to zero.
        if ( typeof window.vote == undefined || window.vote.length == 0 ) {

            $('.error').html("ERRRROOORRRR");

        } else {

            $(".tme").removeClass('clicked');
            $(this).addClass('clicked');
        }
    });
});
</script>
于 2013-05-31T01:04:11.883 に答える