繁体   English   中英

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

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

具有数据 url 属性的 div 必须由链接替换。 链接必须从 div 中获取 data-url 属性。 但是,这应该只发生在鼠标悬停或单击时。

所以这个div:

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

鼠标悬停或点击时应该变成这个

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

我试过这样的事情:

<script>

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

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

});

这可能吗? 非常感谢您的时间和精力。

这是您的操作方法:

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

但是,如果您需要在单击 div 时简单地打开 url,您可以这样做:

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

您可以在动态添加的元素上使用事件委托,并使用mouseover添加a并且在mouseout上它会再次添加div

我们还需要在我们a href元素上使用class以便我们可以使用相同的使用 to on mouseout来恢复原始div

演示

 //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