我尝试使用JQuery和一些JS变量创建链接。 HTML如下:
<script>
$(document).on("click", ".btn", function () {
var $memberid = $(this).data("id");
var $memberName = $(this).data("name");
$(".modal-body #memberName").text($memberName);
$(".modal-footer a").attr("href","/user/delete/" + $memberid);
});
</script>
<div class="panel panel-default">
<div class="panel-heading">All Users</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Operating Capacity</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{ $user->fname }} {{ $user->lname }}</td>
<td>{{ $user->user_type->name }}</td>
<td>
@if($user->position < 4)
<a href="/user/profile/{{ $user->memberid }}" class="btn btn-sm btn-primary">Edit</a>
<button type="button" class="btn btn-sm btn-danger" data-id="{{ $user->memberid }}" data-name="{{ $user->fname }} {{ $user->lname }}" data-toggle="modal" data-target="#myModal">Delete</button>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete User</h4>
</div>
<div class="modal-body">
<p>Are you sure you wish to delete this user?</p>
<p id="memberName"></p>
</div>
<div class="modal-footer">
<a href="" class="btn btn-danger wideButton">Yes</a>
<button type="button" class="btn btn-success wideButton" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
现在这样就可以很好地创建链接了。当模态屏幕打开时,“是”&#39;按钮有
的链接/用户/删除/ someuserid
但是,当您点击该链接时,它会返回一个类似
的网址/用户/删除/未定义
我出错的任何想法?我认为这与变量范围有关,但我不能把手指放在哪里。
非常感谢
加文。
答案 0 :(得分:2)
简单,只要点击具有btn
类的元素,就会调用onclick处理程序:
$(document).on("click", ".btn", function () {
...
});
你的模态链接(是的按钮)有那个类
<a href="" class="btn btn-danger wideButton">Yes</a>
当然,当您单击“是”按钮时,将调用onclick处理程序,其中将再次生成链接的href。但是这次$(this).data("id")
未定义,因为您的“是”按钮没有ID。
var $memberid = $(this).data("id");
var $memberName = $(this).data("name");
$(".modal-body #memberName").text($memberName);
$(".modal-footer a").attr("href","/user/delete/" + $memberid);
TL; DR; 在删除按钮中添加另一个类,例如btn-delete
:
<button type="button" class="btn-delete btn btn-sm btn-danger" data-id="{{ $user->memberid }}" data-name="{{ $user->fname }} {{ $user->lname }}" data-toggle="modal" data-target="#myModal">Delete</button>
并在onclick事件绑定器中使用该类
$(document).on("click", ".btn-delete", function () {
var $memberid = $(this).data("id");
var $memberName = $(this).data("name");
$(".modal-body #memberName").text($memberName);
$(".modal-footer a").attr("href","/user/delete/" + $memberid);
});