onclick on a image to navigate to another page using Javascript

后端 未结 4 2059
刺人心
刺人心 2020-12-13 14:27

I am getting warmed up with Javascript so I am trying something on my own. I am searching for a onclick function, where I have thumbnail images in my index.html page, and wh

相关标签:
4条回答
  • 2020-12-13 14:56

    You can define a a click function and then set the onclick attribute for the element.

    function imageClick(url) {
        window.location = url;
    }
    
    <img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />
    

    This approach lets you get rid of the surrounding <a> element. If you want to keep it, then define the onclick attribute on <a> instead of on <img>.

    0 讨论(0)
  • 2020-12-13 15:15

    I'd set up your HTML like so:

    <img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />
    

    Then use the following code:

    <script>
    var images = document.getElementsByTagName("img");
    for(var i = 0; i < images.length; i++) {
        var image = images[i];
        image.onclick = function(event) {
             window.location.href = this.id + '.html';
        };
    }
    </script>
    

    That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

    0 讨论(0)
  • 2020-12-13 15:18

    Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

    <script>
        $(document).ready(function() {
            $('img.thumbnail').click(function() {
                window.location.href = this.id + '.html';
            });
        });
    </script>
    

    Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

    <img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
    <img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />
    
    0 讨论(0)
  • 2020-12-13 15:19

    maybe this is what u want?

    <a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
        <img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
    </a>
    

    edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....

    0 讨论(0)
提交回复
热议问题