jQuery:在mouseover / hover上创建链接

时间:2014-07-22 22:50:12

标签: javascript jquery

我有以下HTML代码。如何在整个div上创建链接,当人们点击它时会将它们带到特定的链接?基本上是整个DIV上的"<a></a>"标签

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

这是我提出的jQuery脚本,我只是不知道如何在其中建立链接

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

3 个答案:

答案 0 :(得分:3)

我知道这不是你要求的。但是,@ undefined在他对你的帖子的评论中提出了一个很好的观点。

因此,不是仅仅在鼠标悬停时自动转发到另一个页面,为什么不(如果用户不清楚)建议点击将把它们带到其他地方。那更好。

您的加价:

<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';
        });
    });

这是一个小提琴:http://jsfiddle.net/6b8ku/1/

答案 1 :(得分:2)

这个怎么样:

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

鼠标悬停在div上时,您可以更改鼠标图标:

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

这里是JSFiddle: http://jsfiddle.net/9zyeX/

答案 2 :(得分:1)

试试这个,应该将整个地块包裹在一个锚中。

我不确定它的语义是否应该起作用

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

Demo