简体   繁体   中英

jQuery: Create link on mouseover/hover

I have the following HTML code. How can create a link on the entire div which when people click on it would take them to a specific link? basically an "<a></a>" tag on the entire DIV

<div class="unique">
  <div>
    <p>Lines of text</p>
      <p>Extra lines of text</p>
  </div>
</div>

here is my jQuery script i have come up with, i just have no idea how to make the link in it

<script>
$( ".unique" ).mouseover(function() {
  $(this).LINK_TO_A_SPECIFIC_URL;
});
</script>

I know this is not quite what you asked for. But, @undefined made a good point in his comment to your post.

So instead of just auto forwarding to another page on a mouseover why not (if it's not clear to the user) advise that clicking will take them somewhere else. That's just nicer.

Your markup:

<div class="unique">
   <div>
     <p>Lines of text</p>
     <p>Extra lines of text</p>
   </div>
</div>

jQuery:

var fetchContent = $('.unique').html();
$(document).ready(function(){
    $('.unique').on('mouseenter',function(){
        $(this).html('Click here and we\'ll go somewhere else!');
        });

    $('.unique').on('mouseleave',function(){
        $(this).html(fetchContent);
        });

    $('.unique').on('click',function(){
        location.href='go-to-your-url';
        });
    });

Here's a fiddle: http://jsfiddle.net/6b8ku/1/

How about this:

<script>
$( ".unique" ).click(function() {
  window.location = LINK_TO_A_SPECIFIC_URL;
});
</script>

You can change the mouse icon, when mouse over the div :

<script>
$( ".unique" ).mouseover(function() {
  $(this).css( 'cursor', 'pointer' );
});
</script>

here is the JSFiddle: http://jsfiddle.net/9zyeX/

Try this, should wrap the whole lot in an anchor.

I'm not sure if its semantic but should work

$('.unique').after(
  '<a href="http://www.google.com">'+$('.unique').html()+'</a>'
).remove();

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