简体   繁体   English

在鼠标悬停时将 div 更改为 href 链接,然后使用 jQuery 单击

[英]Change div to a href link on mouseover and click using jQuery

A div with a data url attribute must be replaced by a link.具有数据 url 属性的 div 必须由链接替换。 The link must get the data-url attribute from the div.链接必须从 div 中获取 data-url 属性。 However, this should only happen with a mouseover or a click.但是,这应该只发生在鼠标悬停或单击时。

So this div:所以这个div:

<div class="thelink" data-url="https://www.example.com">The Title</div>

should become to this on mouseover or a click鼠标悬停或点击时应该变成这个

<a href="https://www.example.com">The Title</a>

I tried something like this:我试过这样的事情:

<script>

$(".thelink").on('click mouseover', function(){

replaceWith("<a href=\"here data-url\">The Title</a>");

});

Is this possible?这可能吗? Thank you very much for your time and effort.非常感谢您的时间和精力。

Here is how you do it:这是您的操作方法:

$(".thelink").on('click mouseover', function(){
   let dataURL = $(this).data('url');
   $(this).replaceWith(`<a href="${dataURL}">The Title</a>`);
});

But if you need to simply open a url when clicking on a div you can do it like this:但是,如果您需要在单击 div 时简单地打开 url,您可以这样做:

$(".thelink").on('click', function(){
   window.location.href = $(this).data('url');
});

You could use event delegation on dynamically added element and use mouseover to add an a and on mouseout it will add the div back again.您可以在动态添加的元素上使用事件委托,并使用mouseover添加a并且在mouseout上它会再次添加div

We also need to use a class on our a href element so that we can use the same use to on mouseout to bring back the original div我们还需要在我们a href元素上使用class以便我们可以使用相同的使用 to on mouseout来恢复原始div

Demo演示

 //Mouse over function $(document).on('mouseover click', '.thelink', function() { $(this).replaceWith($('<a class="newLink">').text($(this).text()).attr("href", $(this).data("url"))); }); //Mouse out function $(document).on('mouseout click', '.newLink', function() { $(this).replaceWith($('<div class="thelink">').text($(this).text()).attr("data-url", $(this).attr("href"))); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="thelink" data-url="https://www.example.com">The Title</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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