我是 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');
我的 Controller 方法是这样的:
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');
那么事情就按预期工作了
<小时/>请帮我解决这两个问题:
使加载的 div 内容与变量 displaymode 配合使用。 注意:它可能是与我尝试实现的解决方案不同的解决方案。
使函数能够提取被单击元素的 attr("displaymode")。
不是来自具有指定 ID 的元素。 我已经尝试过:
var linkcode = $(this).attr("displaymode");
但与我在网上找到的示例相反,以防我的代码不起作用。
任何帮助表示赞赏。谢谢
最佳答案
更新:
我在您的标记代码中没有看到任何 id“demo3”:
$('#demo3').attr("displaymode"); // creating the variable
我猜您想使用单击 anchor 的“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
大小写。
关于javascript - jquery 创建变量并使用它来加载 - laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27751325/