admin管理员组

文章数量:1322850

I want a background image to change with the onclick attribute on html link tag. But its not working.

<ul>
    <li><a href="index.php?page=Home" onclick="one();">Home</a> </li>
    <li><a href="index.php?page=Achivement" onclick="two();">Achivement</a></li>

    <li><a href="index.php?page=Career" onclick="three();">Career</a></li>
    <li><a href="index.php?page=Message" onclick="four();">Message</a></li>
    <li><a href="index.php?page=opportunity">opportunity</a></li>
    <li><a href="upload1.php">Register</a>
    <li></li>
 </ul>
  <script type="text/javascript">
  function one(){

 $('body').css('background-image','url(image/back1.jpg)');

}
function two(){

   $('body').css('background-image','url(image/back2.jpg)');

}
function three(){


}
function four(){


}  </script>

as you can see I tried passing a function on the onclick attribute and I have already defined these function on the bottom already and still the background image wont change. I have checked the directory where the images are they are correct. and I havent defined any background image on my css so. I need help and its driving me crazy.

I want a background image to change with the onclick attribute on html link tag. But its not working.

<ul>
    <li><a href="index.php?page=Home" onclick="one();">Home</a> </li>
    <li><a href="index.php?page=Achivement" onclick="two();">Achivement</a></li>

    <li><a href="index.php?page=Career" onclick="three();">Career</a></li>
    <li><a href="index.php?page=Message" onclick="four();">Message</a></li>
    <li><a href="index.php?page=opportunity">opportunity</a></li>
    <li><a href="upload1.php">Register</a>
    <li></li>
 </ul>
  <script type="text/javascript">
  function one(){

 $('body').css('background-image','url(image/back1.jpg)');

}
function two(){

   $('body').css('background-image','url(image/back2.jpg)');

}
function three(){


}
function four(){


}  </script>

as you can see I tried passing a function on the onclick attribute and I have already defined these function on the bottom already and still the background image wont change. I have checked the directory where the images are they are correct. and I havent defined any background image on my css so. I need help and its driving me crazy.

Share Improve this question asked Jan 13, 2014 at 15:08 ShanjayGShanjayG 1,0234 gold badges19 silver badges35 bronze badges 9
  • 1 are you included jQuery library?? – Pranav C Balan Commented Jan 13, 2014 at 15:09
  • Any console.log errors? – Sergio Commented Jan 13, 2014 at 15:09
  • 4 Page will be redirected since it is a hyperlink. – Rajaprabhu Aravindasamy Commented Jan 13, 2014 at 15:10
  • So I think the background is changing, but immediately after the change, the link actually redirects to index.php and the page is redrawn fresh. event.preventDefault() might be in your interest to search on. – Arthur Weborg Commented Jan 13, 2014 at 15:11
  • Pass an identifier in the url path which holds the background image index. For example index.php?page=home&background=1. Then in your js create a function to get this param and display the correct image. – Mivaweb Commented Jan 13, 2014 at 15:12
 |  Show 4 more ments

6 Answers 6

Reset to default 2

A couple things:

  1. You need to include the jQuery library (in case you did not already)
  2. You need to prevent the default action because it is a link
  3. You need to functionalize it for reuse.

Example:

<script type="text/javascript">
    $(function(){
        $('a').on('click',function(e){
            var href = this.href.split('='),
                img;

            // prevents following to the link location
            e.preventDefault();

            // determines which background image
            switch(href[1]){
                case 'Home':
                   img = 'back1.jpg';
                   break; 
                case 'Achievement':
                   img = 'back2.jpg';
                   break;
                case 'Career':
                   img = 'back3.jpg';
                   break;
                case 'Message':
                   img = 'back4.jpg';
                   break;
                case 'Opportunity':
                   img = 'back5.jpg';
                   break;
            }

            // assigns background-image
            $('body').css({backgroundImage:'url(image/'+img+')'});
        });
    });
</script>

This will allow great reuse, and eliminate the need for the inline onclick= declarations.

You have an href along with the click. You will need to specify your link as

<li><a href="#" onclick="one();">Home</a> </li>

You will need to redirect to the page through javascript. Otherwise you are in essence asking it to go to redirect you to the URL and call your javascript but if the redirect happens how would you even see what the javascript execution yields?

Remove your inline script and all your functions and try this instead:

$(function () {
    $('ul li a').on('click', function (e) {
        e.preventDefault)();
        $('body').css('background-image', 'url(image/back' + $(this).closest('li').index() + '.jpg)');
    });
});

If you just want to target the first 4 li you can add to my code a if($(this).closest('li').index() < 5){ change background };

About the links you have, if you want to use them

Try to use this stetment for jQuery element:

$(function() {
  $('elementLink').on('click', function(e){
       e.preventDefault();
       $('body').css('background-image','url(image/back1.jpg)');
  });
});

It should be like this:

onclick="one(); return false;"

when you click a link, the new page loads, so you have to prevent this behavior by writing return false

You can also write

onclick="return one();"

and javascript:

function one(){
  $('body').css('background-image','url(image/back1.jpg)');
  return false;
}

I would always try to keep the image src decision out of the code, and move it into the CSS file. Something like:

// could be good to keep your url params as lower case as a convention, then this
// options object could be skipped and you'd just use the param as the classname
var options = {
  'Home': 'home',
  'Achievement': 'achievement'
};

$("ul li a").click(function(e){
  e.preventDefault();

  var href = $(this).attr("href");

  if(href[1])
  {
    $("body").addClass(options[href[1]]);
  }

});

then in your css file

body.achievement
{
  background: url("/images/some_img.png");
}

body.home
{
  background: url("/images/some_img2.png");
}

That way when you want to update the srcs, or styles, you do't have to go searching through the src

p.s. I haven't run the code above, but hopefully you get the idea :)

本文标签: jqueryHow change background image with javascript onClick on a linkStack Overflow