0

シナリオ:

ページの上部 (日、週など) と下部 (フィルター 1 とフィルター 2) にいくつかのボタンがあり、中央にグラフがある単純な html ページが存在します。

グラフには、選択したフィルタに基づくデータが表示されます。

問題:

ユーザーが filter2 を選択すると、データがそれに応じて表示されるように、ユーザーが以前に TOP ボタンで何を選択したかを知る必要があります。

最後に選択したボタンを追跡するためにグローバル変数を使用しています。これは、多くの switch ステートメントを意味します。これがこの問題を解決する最もエレガントな方法なのか、それとも魔法があるのか​​ 疑問に思っています。関数はJqueryに存在します。

4

2 に答える 2

1

data最も簡単な方法は、要素自体で使用することだと思います。

<button id="day" class="graph-button" data-state="off">Day</button>
<button id="week" class="graph-button" data-state="off">Week</button>
<!-- graph here -->
<button id="filter1" class="graph-button" data-state="off">Filter 1</button>
<button id="filter2" class="graph-button" data-state="off">Filter 2</button>

次に、次のような jQuery を使用できます。

$(function(){
    $('.graph-button').click(function(ev){
        ev.preventDefault();

        var state = $(this).data('state'),
            newState = state == 'off' ? 'on' : 'off',
            onButtons = [];

        $(this).data('state', newState);

        $('.graph-button[data-state="on"]').each(function(i, el){
            onButtons.push(this.id);
        });

        // updateGraphWith(onButtons);
    });
});
于 2012-05-21T00:52:19.573 に答える
0

トップボタンclass="topButton"とフィルターボタンがclass="filterButton"あり、すべてのボタンが一意の ID を持っていると仮定すると、jQuery は次のようになります。

$(function(){
    var topButtons = $(".topButton").on('click', function() {
        var $this = $(this);
            id = $this.attr('id');
        if($this.hasClass('selected')) { return; }
        topButtons.removeClass('selected');
        $this.addClass('selected');
        //perform click action here
    });

    $('.filterButton').on('click', function() {
        var $this = $(this);
            id = $this.attr('id'),
            selectedTopButtonId = $('.topButton').filter('.selected').attr('id');
        //perform filter action here
    });
});

どちらの場合も、変数によってidどのボタンがクリックされたかがわかります。

選択したトップ ボタンに設定class="selected"することで、ボタンのスタイルを設定し、グローバル変数に頼らずに何かをテストすることができます。

于 2012-05-21T01:07:11.050 に答える