javascript - Get id of element which raised event - Stack Overflow

I am working in asp mvc. I have following JS<script>function fun(){alert($(this).attr("id&qu

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.

Share Improve this question edited Jul 13, 2020 at 16:04 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 14, 2013 at 19:22 Fakhar uz ZamanFakhar uz Zaman 2997 silver badges22 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Pass 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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744252681a4565242.html

相关推荐

  • javascript - Get id of element which raised event - Stack Overflow

    I am working in asp mvc. I have following JS<script>function fun(){alert($(this).attr("id&qu

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信