jQuery Problem: Can't read href attr for some reason
not sure why this is returning undefined. The element exists and I even tried to change the ID property to ma开发者_JS百科ke sure it wasn't conflicting with anything in the namespace.
I also am importing jquery, so that's not the issue. The double brackets are for Django context variables
Any thoughts?
<script type="text/javascript">
//return to search page with appropriate GET parameters
var parameters=window.location.search +'';
$('#back').attr('href',$('#back').attr('href')+parameters);
</script>
<div id="content">
<a id="back" href="{{site}}search/"><< Return to Search Results </a>
</div>
Make sure you're modifying the attribute after the DOM is fully loaded by putting your code inside a call to $(document).ready():
<script type="text/javascript">
$(document).ready(function()
{
var parameters=window.location.search +'';
$('#back').attr('href',$('#back').attr('href')+parameters);
});
</script>
The code as it appears in your question will fail if the script
tag is inside the body
, because the Javascript will be invoked as it's parsed, and at that point in time, your anchor tag has yet to be parsed.
The following works for me.. maybe you're breaking it by using < instead of <
<div id="content">
<a id="back" href="{{site}}search/"><<Return to Search Results </a>
</div>
<div id='result'>result</div>
$(document).ready(function(){
var parameters=window.location.search +'/';
$('#back').attr('href',$('#back').attr('href')+parameters);
$('#result').html($('#back').attr('href'));
});
Your selector, $("#back") selects an ARRAY of controls. You want to address the [0] element of the array, like this:
<script type="text/javascript">
function hrefOnClick() {
var myA = $("#testHref");
alert(myA[0].href);
}
</script>
for an anchor tag that looks like this:
<a id="testHref" href="http:\\www.stackoverflow.com" onclick="hrefOnClick();">click me</a>
精彩评论