简体   繁体   中英

Using jQuery to change the background image

I am trying to change the background image of a link when it get clicked. I keep getting the error that you cannot call 'click' on null.

JQuery (in the header)

<script type="text/javascript">
    $('a.upvote-arrow').click(function(){
        $('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
    });
</script>

HTML

<div class="top-comment-vote">
    <a href="#" class="upvote-arrow" title="Up vote" id="tempid1"></a>
</div>

Thanks

Try adding $(document).ready :

<script type="text/javascript">
$(document).ready(function(){
    $('a.upvote-arrow').click(function(){
        $(this).css('background-image','url(../images/icons/up-arrow2.png)');
    });
})
</script>

Are you sure this script is being loaded after the html is in the DOM?

Try wrapping what you wrote in a onload closure.

$(function() {
 $('a.upvote-arrow').click(function(){
   $('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
 });
});

Another thing you can do is take advantage of delegation for the event registration.

$('body').on("click", ".a.upvote-arrow", function(){
 $('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});

This binds it to the body instead.

Try wrapping your script with document.ready; I suspect that you're script might be running before your entire page loads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM