jQuery结合了多个元素 [英] jQuery combine multiple elements
问题描述
我正在尝试jQuery
,遇到了一个问题.我可以将具有现有element
的actual selector
用作jQuery的组合选择器吗?
I was experimenting with jQuery
and came across a question. Can I use an actual selector
with existing element
as a combined selector for jQuery?
因此,假设我即时创建了一个DIV
元素:
So, suppose I've created a DIV
element on-the-fly:
var $div = $('<div>')
.css('position', 'absolute')
.hide(); // Just to be short
$('body').append($div);
当用户将鼠标悬停在P
元素/段落(在光标位置处)时,我想显示它:
And I want to show it when user hovers over P
elements / paragraphs (at the cursor position):
$('p').hover(function(e) {
// Change the position of $div with regards of cursor position
$div.show();
}, function(e) {
$div.hide();
});
但是,我也想将此hover
处理程序应用于$div
本身.因此,我不想复制我的代码,而是要做这样的事情:
BUT also I want to apply this hover
handlers to $div
itself. So instead of duplicating my code, I want to do something like this:
$('p', $div).hover(...)
,它将选择$div
元素以及所有P
元素.
which will select $div
element along with all P
elements.
我知道我可以单独编写函数,并将名称作为参数传递给hover
函数.
I know I can write functions separately and pass the names as arguments to hover
function.
在jQuery中这种情况是否有解决方案?还是有一个更准确的解决方案?
Is there any solution to this kind of situation in jQuery? or is there a more accurate solution?
推荐答案
您可以使用jQuery 添加方法:
You could use the jQuery add method:
$('p').add($div).hover(function(e) { ...
这篇关于jQuery结合了多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!