Accessing The pathname of an anchor tag
I can see the value of the pathname of my anchor tag in firebug, but I am having a hard time accessing it
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
alert("Hi");
$.ajax({
type: "POST",
url: "NickTracker.asmx/LogActivity",
contentType: "application/json; charset=utf-8",
data: "{'path': '" + attr('pathname') + "'}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
</script>
Here is my html
<body>
<form id="form1" runat="server">
<div>
Page 1<br />
<br />
<a href="http://manual.aspdotnetstorefront.com/p-157-xml-packages.aspx">Manual</a>
<br />
<a href="http://www.google.com/">googles</a>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</div>
</form>开发者_开发知识库;
</body>
When a user clicks I want the path returned, this doesnt work-attr('pathname')
You need to reference the this
object and the correct attribute, so replace attr('pathname')
with $(this).attr('href')
or even more simply this.href
this.pathname
will only access any value after the URL hostname, which is fine if you're traversing root-relative files on your site, but will break if you're trying to access files on a different host. For example, for href="http://www.google.com/finance"
, this.pathname
would result in just /finance
If you mean the href attribute or even an attribute called pathname you will need to fix your attr call. What you have currently will look for a function called attr and try to pass it a string. Try: $(this).attr("href")
or $(this).attr('pathname')
or this.attribute("href")
. It depends on if you are looking for an attribute you added to the anchor called pathname or the href attribute.
Supposedly, all it takes is just something like
$('a').attr('href');
Now if you had many different <A>
tags in your document, that'll be a problem. You'll have to differentiate with tag you mean. Normally you do that with ids or classes.
$('a#myAnchor').attr('href');
精彩评论