Get information of element that called function with jQuery

怎甘沉沦 提交于 2020-01-02 05:59:30

问题


I was wondering how I'd go about finding with jQuery, the element id that called an onClick method? my code is:

JS

function getInfo(event)
{
    console.log(event.target.id + " ... ");
}

HTML

<div class="menu-content" id="thisismyid">
    This is some placeholder text.<br>
    <a onClick="getInfo()" id="thisisthelinksid">Click on me</a>
</div>

<div class="menu-content" id="thisismysecondid">
    This is some more placeholder text.<br>
    <a onClick="getInfo()" id="thisistheotherlinksid">Click on me</a>
</div>

I can't put anything inside the parentheses of the function, because I want a function passed to it later, I just want to be able to tell which called this function.

I know this has been asked many times, and a lot of the questions have answers, but I have read through a lot of them and none have helped me.

Thanks guys

-EDIT-

In regards to the answers below at time of this edit, I cannot use the jQuery method like:

$("div.menu-content a").click(function() {
    some content here..
});

because I need it to only be run on certain links being clicked, not all of them. Does that help clarify?


回答1:


$("div.menu-content a").click(function() {
    var $elemId = $(this).attr("id");
    console.log($elemId + " .... ");
);

Is a much more "jQuery style" solution to do it.




回答2:


Try:

function getInfo(event)
{
    var id = $(event.target).attr('id');
    console.log(id);
}



回答3:


Don't use the onclick attributes, use event handlers instead.

$(function(){
   $('a', 'div.menu-content').click(function(){
      console.log(this.id+'...');
   });
}):


来源:https://stackoverflow.com/questions/7555421/get-information-of-element-that-called-function-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!