I am working in asp mvc. I have following JS
<script>
function fun()
{
alert($(this).attr("id"));
}
</script>
And following code in View
@
{
int i=1;
}
@for(i=1;i<10;i++)
{
<a href="" id="@i" onclick="fun()">ABC</a>
}
I want to get ID of anchor which calls fun()
, but i get undefined
value always. Please help.
I am working in asp mvc. I have following JS
<script>
function fun()
{
alert($(this).attr("id"));
}
</script>
And following code in View
@
{
int i=1;
}
@for(i=1;i<10;i++)
{
<a href="" id="@i" onclick="fun()">ABC</a>
}
I want to get ID of anchor which calls fun()
, but i get undefined
value always. Please help.
4 Answers
Reset to default 4Pass this
<a href="" id="@i" onclick="fun(this)">ABC</a>
function fun(elem) {
alert(elem.id);
}
In the case you are refering to , this will refer to the window object . So if you pass the element to the function
, that elemnent will be available in the scope of the function which acts as a closure.
Try:
<script>
function fun(el) {
alert($(el).attr("id"));
}
</script>
and:
@
{
int i=1;
}
@for(i=1;i<10;i++)
{
<a href="" id="@i" onclick="fun(this)">ABC</a>
}
If i absolutely had to do it with an onclick attribute, i would call the function with this
as the context, and while i'm at it, pass the event object.
<a href="" id="@i" onclick="fun.call(this,event)">ABC</a>
(no changes needed to fun
method)
Yes, that because you have to send the object itself in the onclick event like this:
@for(i=1;i<10;i++)
{
<a href="" id="@i" onclick="fun(this)">ABC</a>
}
And then you can access to its properties:
<script>
function fun(obj)
{
alert(obj.id);//obj.name, obj.value also you could take.
}
</script>