我有一个Razor表单,它有多个链接调用一个动作,我试图压缩jQuery。链接如下:
<a id="approveModal"
href="#"
data-id=""
data-payload='{"Id": "@item.Id","projectId": "@item.ProjectId"}'
data-toggle="modal"
data-target="#actionConfirmation"
data-actiontype="approve"
class="fa fa-thumbs-up fa-2x wfAction">
</a>
并且我调用的函数如下所示:
$(document).on("click", ".wfAction", function () {
var sender = $(event.target).attr('id');
var stepId = $("#approveModal").data("payload").Id;
var projectId = $("#approveModal").data("payload").projectId;
最初我传入了#approveModal,当时我只有一个按钮,但现在我正在尝试将click事件分配给链接上的类。我需要根据发送请求的链接访问各个属性,但是我被卡住了。
答案 0 :(得分:1)
将click事件绑定到元素后,当调用该函数时,函数的主要范围是您的元素,因此如果使用event
,您将访问该元素本身,那个功能。有了这个,你只需要像以前一样获得参数。
是基于原始代码的示例代码。
另外,如果您打算像往常一样使用function(event){...}
,则需要将其作为参数$(document).on("click", ".wfAction", function () {
var sender = $(this).attr('id');
var stepId = $(this).data("payload").Id;
var projectId = $(this).data("payload").projectId;
console.log(this);
console.log('stepId: ' + stepId + ' | projectId: ' + projectId)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="approveModal"
href="#"
data-id="test1"
data-payload='{"Id": "1","projectId": "project one"}'
class="fa fa-thumbs-up fa-2x wfAction">test 1
</a>
<br>
<a id="approveModal1"
href="#"
data-id="test2"
data-payload='{"Id": "2","projectId": "project two"}'
class="fa fa-thumbs-up fa-2x wfAction">test 2
</a>
<br>
<a id="approveModal2"
href="#"
data-id="test3"
data-payload='{"Id": "3","projectId": "project three"}'
class="fa fa-thumbs-up fa-2x wfAction">test 3
</a>
&#13;
.container {
width: 50px;
overflow: auto;
}
&#13;