jquery创建变量并使用它来加载 - laravel

jquery creating variable and using it to for load - laravel

本文关键字:加载 laravel 创建 变量 jquery      更新时间:2023-09-26

我是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 内容与变量显示模式一起使用。注意:它可以是与我尝试实现的解决方案不同的解决方案。

  2. 使函数工作提取被单击的元素的attr("显示模式")。

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

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

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

任何帮助表示赞赏。感谢

更新:

我在标记代码中没有看到任何 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案例。