开发者

Getting the ID of an object when the object is given

开发者 https://www.devze.com 2022-12-25 13:47 出处:网络
I have link that calls a function when clicked: <a href=\"javascript:spawnMenu(this);\" id=\"link1\">Test1</a>

I have link that calls a function when clicked:

<a href="javascript:spawnMenu(this);" id="link1">Test1</a>

To make my function work, I need access to the object so th开发者_Go百科at I can perform jQuery operations like this:

alert($(objCaller).offset().left);

Since objCaller points to the object and not the object ID, this won't work. I need something like this:

alert($("a#link1").offset().left);

How can I get the object ID from objCaller?


You need to do this:

<a href="javascript:;" onclick="spawnMenu(this);" id="link1">Test1</a>

You can't pass this via a javascript: url.


Doesn't this work?

objCaller.id


Just off the top of my head: does alert($(this).offset().left); not work? Otherwise, you can get the ID via $(this).attr("id").


It's not clear from your question what objCaller refers to. If it refers to the element itself, then $(objCaller) would work fine with jQuery.

Try your code using firebug (an extension for firefox). You can swap 'alert' for 'console.log' so you have:

console.log(objCaller);

This will help you work out exactly what is stored in objCaller (it isn't an element if $(objCaller) isn't working, as I say).

If objCaller is an element, then objCaller.id would be the way to retrieve the id.


You can get the ID by doing this:

function spawnMenu (elem) {
    var id = elem.id; // elem is just a DOM node, so access it's id

    // your code here...
}

However, jQuery should also be able to wrap a DOM node, so the following should work as well:

function spawnMenu (elem) {
    elem = $(elem).get(0);

    // your code here...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消