[英]How to Show Dynamically Added Element
I'm trying to create tooltips with title attribute and jQuery but can't find method to show dynamically added element. 我正在尝试创建具有title属性和jQuery的工具提示,但找不到用于显示动态添加的元素的方法。
HTML HTML
<a href="/some-page" title="Show tooltip" class="dfn">some page</a>
CSS CSS
.tooltip {
…
display: none; /* I's needed for hard coded tooltips */
…
}
jQuery jQuery的
$(function () {
if (window.matchMedia('(min-width: 980px)').matches) {
$('.dfn').hover(
function () {
var el = $(this);
var txtTitle = el.prop('title');
el.append('<p class="tooltip">' + txtTitle + '</p>');
//That's it. My tooltip has been created, but it has not been shown
$(el + ' .tooltip').show('fast');
el.data('title', el.prop('title'));
el.removeAttr('title');
}, function () {
$(el + ' .tooltip').hide('fast').remove();
el.prop('title', el.data('title'));
}
);
}
});
As mentioned by others, $(el + ' .tooltip').show('fast');
正如其他人所提到的,
$(el + ' .tooltip').show('fast');
is probably wrong. 可能是错误的。
The el is an object, not a string to concat', one way is to use el.find('.tooltip').show()
. el是一个对象,而不是要连接的字符串,一种方法是使用
el.find('.tooltip').show()
。
The other way is to use the context option: $('.tooltip', el).show();
另一种方法是使用上下文选项:
$('.tooltip', el).show();
You need to have correct code to find new element: 您需要正确的代码才能找到新元素:
$('.tooltip', el).show('fast');
Your current one probably endup searching for something like [object] .tooltip
or similar string depending on how JavaScript decides to convert HTML element to string. 您当前的脚本可能最终会根据JavaScript确定将HTML元素转换为字符串的方式来搜索
[object] .tooltip
或类似字符串。
As others have mentioned el.find('.tooltip').show()
and el.find('.tooltip').hide().remove();
正如其他人提到的
el.find('.tooltip').show()
和el.find('.tooltip').hide().remove();
solve the problem. 解决这个问题。
Also, in HandlerOut function, you el was not declared. 另外,在HandlerOut函数中,未声明您。 Fiddle here
在这里摆弄
$(function () {
//if (window.matchMedia('(min-width: 980px)').matches) {
$('.dfn').hover(
function () {
var el = $(this);
var txtTitle = el.prop('title');
el.append('<p class="tooltip">' + txtTitle + '</p>');
//That's it. My tooltip has been created, but it has not been shown
el.find('.tooltip').show()
el.data('title', el.prop('title'));
el.removeAttr('title');
}, function () {
var el = $(this);
el.find('.tooltip').hide().remove();
el.prop('title', el.data('title'));
}
);
//}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.