jquery 创建变量并将其用于加载 - laravel

jquery creating variable and using it to for load - laravel

我是 jQuery 的新手,虽然我已经阅读了一些教程,但显然我不太了解一些基础知识。

我有两个按钮:

<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');  

那么一切正常


请帮我解决这两个问题:

  1. 使加载 div 内容与变量 displaymode 一起工作。 注意:它可能是与我尝试实施的解决方案不同的解决方案。

  2. 使函数工作提取被单击元素的属性("displaymode")。

不是来自具有指定 ID 的元素。 我试过这个:

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

但与我在网上找到的示例相反,如果我的代码不起作用。

感谢任何帮助。谢谢

更新:

我在您的标记代码中没有看到任何 ID“demo3”:

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

我猜你想使用点击锚点的“显示模式”属性,所以为此你可以将 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 个案例。