Very simple jQuery attribute question
Either I have misunderstood the jQuery docs for .attr(), or I'm making a very stupid error.
Why isn't this working?
<div id="mydiv" title="mytitle"></div>
<script type="text/javascript">
$(document).ready(function(){
var username = $("#my开发者_如何学运维div").attr("title");
alert(username);
});
</script>
I just get 'undefined' in the alert.
Works fine for me.. http://jsfiddle.net/6NG4P/
Are there any other alerts on the page that may be causing the issue or is it possible the library isn't loading correctly (like $
has a conflict) or there is another div
with the same id
without a title
attribute?
What you have works, you can test it here, make sure you don't have another id="mydiv"
element earlier in the page - it's both invalid HTML and usually the result will be $("#mydiv")
finding the first occurrence, which may not have that attribute.
Your code works fine for me as it looks fine
It is probable that surrounding code is doing something wrong.
Make sure that:
- You have loaded the jquery library in the page
- There is not conflict if you are using some other library
精彩评论