using jQuery attr('onclick') returns undefined
I'm trying to access the 'onclick' attribute of a dynamically generated link:
<div class="IDX-linkVirtualTour">
<p class="detailsLink_p">Virtual Tour</p>
<div class="IDX-detailsSubLink">
<a onclick="window.open('http://www.tourfactory.com/736220', 'VirtualTour', 'width=800, height=600, resizable=1, scrollbars=1, status=0, titlebar=0')" href="javascript:void(0)">Virtual Tour</a>
</div>
</div>
Element as it appears in firebug ^
I can access the href attribute by:var $sublinkA = $('.IDX-detailsSubLink a');
log(
$sublinkA[0].开发者_JAVA百科href +
"\n" +
$sublinkA[0].onclick); // output the value to firebug console
Output to firebug console:
http://www.vdbestates.com/... (intentionally shortened) undefinedAny ideas?? Thanks!
(EDIT) ANSWERED:
var $sublinkA = $('.IDX-detailsSubLink a')
refers to multiple elements, although not each of these element's tags have the onclick attribute. I realized, only one of the elements have it. I restructured the jQuery as such:
var $virtualLink = $('.IDX-linkVirtualTour .IDX-detailsSubLink > a');
log("onclick: " + $virtualLink.attr('onclick'));
and obtained the value of the onclick attribute. Moral of the story, be careful trying to access attributes of a set of elements, because they may not all have the desired attribute, hence returning undefined.
Cheers!
If you are just trying to access the value of the onclick
attribute, then you can do this:
$("elementID").attr("onclick");
To fit this in with what you've already got, it would look something like this:
var $sublinkA = $('.IDX-detailsSubLink a');
var onclickAttr = $($sublinkA[0]).attr("onclick");
Considering that the href
from the console message is different from that in your HTML, I'd say that the element at index [0]
is different than the one you're targeting.
If you have multiple instances of .IDX-detailsSubLink a
, then you're grabbing the first.
If you have only one on the page, then it returns the function that wraps the content of your inline onclick
.
If you want the actual attribute, you can use getAttribute()
instead.
var $sublinkA = $('.IDX-detailsSubLink a');
log(
$sublinkA[0].href +
"\n" +
$sublinkA[0].getAttribute('onclick'));
But you still need to be referencing the correct element.
精彩评论