Get the ID of the caller in JavaScript/JQuery
I've created an AjaxMethod (a very general method, and I'm doing ASP.NET MVC ) to get the ID of the item the user clicks on, to add them into the site cart (by adding them to the cookies). The problem is that my Ajax method has one parameter which is used as the ID so I'm creating buttons whose id attribute are the actual product ID and their values are Add to Cart . I've also created a single hidden submit button whose id is the same name as the parameter name in Ajax method and its value depends on the ID of the clicked button .
Click Button ID --Passed into--> Value of submit button
My problem is, I wanna know that is there any way to write a JavaScript/JQuery method and use it in OnClientCLick in the buttons to: get the id of the caller button and then pass it to the value of the submit button.
For example:
// I do not know the ID of the caller
// this method is used like: <button id="1111" OnClientClick="Test()"></button>
function Test() {
var ID = this.id // this did not work
$("#SubmitButton").val(ID)
$("SubmitButton").trigger("click")
}
First off there is a problem with your function, this
does not actually refer to the button in that context.
You need to define the function to match the standard event handler signature, something like:
function Test(event)
Then you can get the Element's ID from the event object as Dmitry showed in his answer:
function Test(event) {
var ID = event.id
$("#SubmitButton").val(ID);
$("SubmitButton").trigger("click");
}
And as you discovered you need to pass in the value for event
in your binding
<button id="1111" OnClick="Test(this);"></button>
Alternatively you can use jQuery to bind the button using something other than the ID:
//set it up like this: <button id="1111" class="SomeClassToIdentifyTheButton"></button>
$(".SomeClassToIdentifyTheButton").click(function(){
var ID = $(this).attr('id');
$("#SubmitButton").val(ID);
$("SubmitButton").trigger("click");
});
您可以使用jQuery .click方法来获取单击元素的ID。
$("#SubmitButton").click(function(event) {
alert(event.target.id);
});
链接地址: http://www.djcxy.com/p/83302.html
上一篇: 从表jQuery获取锚标记类/标识