[英]Javascript / jQuery: Why do I keep getting undefined?
I have the following html code: 我有以下html代码:
<a class="tabTitle" id="title_boxtab_default" tab-type="default" href="#tabs-3">Sample</a>
In jQuery I'm trying to get the value of the href attribute with: 在jQuery中,我尝试使用以下方法获取href属性的值:
$('.tabTitle').last().attr('href');
But it keeps telling me it's undefined? 但是它一直告诉我它是不确定的吗?
I should mention that the number of links with class"tabTitle" increases. 我应该提到的是,带有“ tabTitle”类的链接的数量增加了。 That's why I use .last() 这就是为什么我使用.last()
Works just fine for me in JSFiddle. 在JSFiddle中对我来说效果很好。 I changed it to this, and it returned #tabs-3
: 我将其更改为此,并返回#tabs-3
:
alert($('.tabTitle').last().attr('href'));
My guess is that it's not running from a ready handler like this: 我的猜测是它不是从这样的就绪处理程序运行的:
$(function() {
var x = $('.tabTitle').last().attr('href');
});
It should work. 它应该工作。 Make sure you are running the script when the element is present in the DOM, f.ex using .ready()
: 确保元素在DOM中存在时正在运行脚本,f.ex使用.ready()
:
$(function() {
alert( $('.tabTitle').last().attr('href') );
});
DEMO: http://jsbin.com/IyeSacU/1/edit 演示: http : //jsbin.com/IyeSacU/1/edit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.