我有多个按钮可以调用相同的JQuery函数。 html示例:
<tr><td>...</td>
<td><button class="modify" name="8">Modify</button></td>
</tr>
<tr><td>...</td>
<td><button class="modify" name="9">Modify</button></td>
</tr>
依旧......
我的JQuery功能:
$(function() {
var id = $("button").attr("name");
$("#dialog").dialog({
autoOpen: false,
height: 250,
width: 240,
modal: true,
buttons: {
"Submit": function() {
$( this ).dialog( "close" );
$.ajax({
url: 'my_http',
type: 'POST',
data: $my_data,
});
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$(".modify").click(function () {
$("#dialog").dialog("open");
}
});
如你所见,我现在需要点击哪个按钮(我在对话框功能的开头检索它的名字)。但由于它的“可点击性”是由类决定的,而不是id,我得到列表中的第一个id(在这种情况下为8,即使点击了第9个)。
我怎么知道哪一个被点击了?如果我使用类,我不知道id(名称),如果我使用id,我怎么知道它被点击了?
答案 0 :(得分:4)
在click()
方法内:
$(".modify").click(function () {
/* 'this' is the clicked DOM node,
'$(this)' is the clicked DOM node wrapped in a jQuery object. */
var clickedButtonName = this.name;
/* or $(this).prop('name'), but don't use jQuery to access a property that
can be returned by the DOM API, it's needlessly expensive. */
$("#dialog").dialog("open");
}
答案 1 :(得分:1)
您可以使用click函数的第一个参数:
$(".modify").click(function (e) {
console.log(e.target);
});