Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - 如何使用jQuery获取href值?(How to get href value using jQuery?)

I'm trying to get href value using jQuery:(我正在尝试使用jQuery获取href值:)

<html> <head> <title>Jquery Test</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function() { $("a").click(function(event) { alert("As you can see, the link no longer took you to jquery.com"); var href = $('a').attr('href'); alert(href); event.preventDefault(); }); }); </script> </head> <body> <a href="http://jquery.com/">jQuery</a> </body> </html> But it doesn't work.(但它不起作用。) Why?(为什么?)   ask by Adi Sembiring translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need(你需要)

var href = $(this).attr('href'); Inside a jQuery click handler, the this object refers to the element clicked, whereas in your case you're always getting the href for the first <a> on the page.(在jQuery单击处理程序中, this对象引用单击的元素,而在您的情况下,您总是获取页面上第一个<a>的href。) This, incidentally, is why your example works but your real code doesn't(顺便说一句,这就是为什么你的例子有效,但你的真实代码没有)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...