1

私はjQueryの初心者です。いくつかのチュートリアルを読んだことはありますが、明らかにいくつかの基本を本当に理解していません。

私は2つのボタンを持っています:

<a id="test1" onclick="getbyText()" displaymode="newcontent/events/newest">News 1</a>

<a id="test2" onclick="getbyVar()" displaymode="newcontent/events/oldest">News 2</a>

<a id="test_output"> - - -</a>

それらを使用して、 id="dashcontent" で div のコンテンツをロードしたい

私のルートは次のようになります。

Route::get('newcontent/latest_events/{mode}', 'ReportsController@newcontent_partials');

私のコントローラーメソッドはこれです:

public function newcontent_partials($mode)
{


    if($mode == 'importance') {

    $rnd = rand(4, 5);  // just for testing purpose

    $top5events = Event1::
            ->orderBy('id', 'desc')
            ->take($rnd)
            ->get();

    $test_type = 'ajax OK - OLDEST';
    }
    else {

    $rnd = rand(5, 6);

    $top5events = Event1::
            ->orderBy('id', 'asc')
            ->take($rnd)
            ->get();

    $test_type = 'ajax OK - NEWEST';


    }


return View::make('partials._event_minibox', compact('test_type','top5events','rnd'));
}

私のスクリプトは次のようになります。

これは期待どおりに機能します。

function getbyText() {
$("#dashcontent").toggleClass( "col_12" );  // just to see that the script is working
$('#dashcontent').load('newcontent/latest_events/newest');
}

これは、ロード ターゲットがプレーン テキストとして配信される場合にのみ機能します。

function getbyVar() {
$('#test_output').text($('#test2').attr("displaymode"));  // printing the value of attr
var linkcode = $('#demo3').attr("displaymode"); // creating the variable 
$('#dashcontent').load(linkcode);  // THIS WILL NOT LOAD 
$('#test_output').text(linkcode); // surprisingly, this one works!!!
}

上記のコードで getbyVar 関数を使用する場合

$('#dashcontent').load('newcontent/latest_events/newest');  

その後、物事は期待どおりに機能しています


これら2つの問題を解決するのを手伝ってください:

  1. 読み込み中の div コンテンツを変数 displaymodeで機能させます。注: 実装しようとしているソリューションとは異なるソリューションになる可能性があります。

  2. クリックされた要素のattr("displaymode")を抽出する機能を動作させます。

指定された ID を持つ要素からではありません。私はこれを試しました:

var linkcode = $(this).attr("displaymode");

しかし、コードが機能しない場合に備えて、オンラインで見つけた例とは対照的です。

どんな助けでも感謝します。どうも

4

1 に答える 1

1

アップデート:

マークアップ コードに ID「demo3」がありません。

$('#demo3').attr("displaymode"); // creating the variable 

クリックされたアンカーの「displaymode」属性を使用したいと思うので、このためにthis引数として渡すことができます:

onclick="getbyText(this)"  
onclick="getbyVar(this)"

次に、関数で:

function getbyText(elem) {
    // use elem as a clicked elem.
}

function getbyVar(elem) { // elem is clicked element
    $(elem).attr("displaymode"); // get the attr of clicked elem
}

またはより目立たない方法:

$('a[id^="test"]').on('click', function(e){
    if(this.id === "test1"){
       // code for test1
    }else if(this.id === "test2"){
       // code for test2
    }
});

switchここでケースを使用することもできます。

于 2015-01-03T03:15:51.327 に答える