我试图在另一个 ID 中显示来自一个 ID 的文本,但它只能工作一次。所以我加载页面,将鼠标悬停在带有 ID 的标题上,然后悬停在另一个标题上,它就停留在第一个上。
HTML
<div class="cp_widget_content" id="portfolio_content_area">
<b class="cp_widget_title" id="portfolio_title_area">'.get_the_title().'</b>';
<div id="title_hover">Test</div>
jQuery
jQuery(document).ready(function()
{
(function ($)
{
$('#portfolio_title_area').hover(function()
{
$('#title_hover').text($('#portfolio_title_area').text());
});
})(jQuery);
});
最佳答案
对我来说,您的评论表明您有多个标题,悬停时应显示在 #title_hover
中。如果是这样,请不要使用 id,使用类选择器,例如:
jQuery(function ($) {
// keep a reference to the target, so we
// don't need to query on every enter/leave
const $title = $('#title_hover');
// store original text
const fallback = $title.text();
$('.cp_widget_title').on({
// on enter
'mouseenter': function() {
// overwrite with text from hovered element
$title.text($(this).text());
},
// on leave
'mouseleave': function() {
// reset to previous text
$title.text(fallback);
},
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="cp_widget_title">Some title 1</b>
<b class="cp_widget_title">Some title 2</b>
<b class="cp_widget_title">Some title 3</b>
<b class="cp_widget_title">Some title 4</b>
<div id="title_hover">Test</div>
附带说明一下,关于在 noConflict
模式下以 $
获取对 jQuery
的引用的样板,而不是:
jQuery(document).ready(function() {
(function ($) {
// code
})(jQuery);
});
你可以使用下面的,这是等价的:
jQuery(function ($) {
// code
});
关于javascript - 在其他 ID 中显示来自 ID 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893381/