最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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>
发布评论

评论列表(0)

  1. 暂无评论