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



具有数据url属性的div必须由链接替换。链接必须从div中获取数据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>");
});

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

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

我们还需要在ahref元素上使用class,这样我们就可以在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>

以下是您的操作方法:

$(".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');
});

最新更新